my dog learned polymorphism
The moose likes Beginning Java and the fly likes Simple stream read question ... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Simple stream read question ..." Watch "Simple stream read question ..." New topic

Simple stream read question ...

Michael Yuan
Ranch Hand

Joined: Mar 07, 2002
Posts: 1427
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!

Seam Framework:
Dave Landers
Ranch Hand

Joined: Jul 24, 2002
Posts: 401
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.
I agree. Here's the link:
subject: Simple stream read question ...
It's not a secret anymore!