Win a copy of Murach's Python Programming this week in the Jython/Python forum!
    Bookmark Topic Watch Topic
  • New Topic

Random access reads and writes  RSS feed

 
Ron Aronica
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Report post to moderator
I am writing strings to a random access file and then attempting to read them back, but I am having a problem. If I use the following code to write the data:
byte[] b = new byte[3]; //size of field
b = new String("Ab").getBytes(); //The data is only 2 characters
file.write(b);
The result is writing the bytes: 65, 98, 0.
Using file.read(b), I read back the same data, but when I try to convert it to a String using,
String s = new String(b, 0, 3), s contains "Ab*" where * is an unknown character.
How to I convert my 3 bytes into the proper 2 character String?
 
Ron Aronica
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Report post to moderator
I now realize that this is a byte/String conversion issue and not an I/O issue. I'm asking the question in the JavaInGeneral forum. Sorry for takeing your time.
 
Francis Siu
Ranch Hand
Posts: 867
  • Mark post as helpful
  • send pies
  • Report post to moderator
hi Ron
I am writing strings to a random access file and then attempting to read them back, but I am having a problem. If I use the following code to write the data:

humm...
Case 1
You want to write a string to a binary file which action can convert the string to binary type.And then, read the string out to the string format and display to the output.
Actually,if in this case,you do not need to do convertion yourself because some method in some class help you to do the convertion.
Or
Case 2
You only do the convertion from string to byte and then,convert it to the string.
If I predict wrong and you need some code about case 1,please reply
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Report post to moderator
Let's put followups in this new thread in Java in General - Advanced. Thanks.
 
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!