Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to read bytes to string regardless of encoding?

 
Grzegorz Klebus
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I came across the following problem: I'd like to read a file into a string so that each byte is converted to a character by just setting the MSB to '\0' and LSB to the byte itself. I know there is a way of doing that (readLine() from java.io.DataInputStream), but the specs say its deprecated:

Deprecated. This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:

with:


I think, however, that the latter solution uses the default encoding to convert bytes to characters (that's what InputStreamReader is for anyway).
How to accomplish what I need without using deprecated methods?
Greg
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then I suggest you read it into a byte array using read(byte[] b, int offset, int len) This will give you a byte array with just the LSB and you can process from there.
Hope this helps
 
Grzegorz Klebus
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Carl,
Thanks for your input. I know it is a solution, and I'm actually using it. The problem, however, remains--now, how to change byte[] to a String without using deprecated methods (you know, Strings are nicer to work with than raw byte arrays ). Do I really have to construct the string myself char after char?
Greg
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you just want to use java's method of converting a byte[] to a String then you can simply use String xxx = new String(b) but, if your hav differing requirements then you will need to increment through the array and convert each byte to a char and add it to a string. I tried to find out how String converts a byte[] to a string by looking at the source code for String but, it uses a Sun class sun.io.ByteToCharConverter which the source isn't included with jdk1.2.2's source code so....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic