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
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’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com