• Post Reply Bookmark Topic Watch Topic
  • New Topic

Convert byte[] to StringBuffer  RSS feed

 
Russell Bateman
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've read a byte array from an open file stream and need to display the contents. It appears that



only prints the address (goop, in fact). Googling, I am unable to find a means of doing this. I have tried:



but this doesn't work. I guess I could resort to printing out the bytes one by one, but how fun is that?
 
Joe Ess
Bartender
Posts: 9439
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This should work:
 
Russell Bateman
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. That does it, of course.
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What String str = new String(bytes) does it to create a java String (i.e. UTF-16) using the default platform character encoding (for windows 2000 this is cp1252).

If the byte array was created from a string encoded in the platform default character encoding this will work well.

If not you need to specify the correct character encoding (Charset) as
String str = new String (byte [] bytes, Charset charset)
 
Russell Bateman
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks very much. I only needed a quick way to get data read from FileInputStream.read() quickly out to System.out.println() for debugging purposes. However, knowing about the encoding problem will come in handy for a real application.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!