Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple stream read question ...

 
Michael Yuan
author
Ranch Hand
Posts: 1427
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple question ... Thanks in advance!
What is the most efficient and elegant way to read an InputStream into a byte array? I mean, read the stream until you hit EOF and then output a byte array. I do not know the size of the stream in advance.
I could do it with a StringBuffer (read a byte at a time and append the byte to a StringBuffer). But that requres converting byte values back and forth with char values.
Any better solutions? Thanks!
Michael
 
Dave Landers
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, you don't want to convert byte data to a String because of the encodings. Encodings translate to/from a local method of storing strings (like ASCII or Shift-JIS) to Unicode used by Java Strings. These encodings may appear to work (if you are in the US or using an 8-bit clean ASCII encoding), but if you move to another machine with a different default encoding (like, say you send your code to someone in another country), the encodings will change and you are likely to corrupt the data.
Use a ByteArrayOutputStream. Read your data from the input and write it to a ByteArrayOutputStream. Then get the byte array from toByteArray().
For efficiency, you should also wrap your streams in Buffered input and output streams.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic