martes, 17 de julio de 2012

Stream of bytes

Today's post is a short one.

So I was playing with streams, and by playing I mean I had to deal with them at work :P

Any way, I do know that unless you are absolutely sure about the content of the stream you should treat them as bytes always, but I made the mistake to handle them as string.
Any way that lead me to find Apache Commons IO, in particular IOUtils.

As it turns out I needed to read all the content from an HTTPInputStream and then returned as byte array.
For those of you who don't see the problem here, the thing is that it's a pain to read something of an input stream at place it in an array. Just to much code for something so simple. Even more if it's a byte array.

Any way a good friend of mine introduce me to this portion of the Apache common library.
(Do take a look at his blog it's just awesome)

And as a result here are the two lines of code that you'll need to do just that i.e. read from an input stream and place the content in a byte array:


import org.apache.commons.io.IOUtils;

return IOUtils.toByteArray((InputStream) yourObjecStream.getStream());


So that's it, please note the casting of the yourObjectStream is just a copy paste hehe.
Hope you enjoy it.


1 comentario:

  1. Woow man, this is great. Great post and great blog. You need to do something with the style and colors though unless you want your readers to turn blind.

    Another cool stuff of the API for streaming is the copyLarge() for streams that are over 2Gb

    ResponderEliminar