Search code examples
arraysbytestream

Android: does ByteStreams.toByteArray change content of source


In my code I want the following functionality :

InputStream is = getInputStream()
byte[] buffer = ByteStreams.toByteArray(is);
function1(buffer)
function2(is)

But what I observe is that if ByteStreams.toByteArray(is); is called then function2 is not working properly. It works fine if I comment that particular line. Also it works fine if I convert buffer back to stream; i.e. function2( new ByteArrayInputStream(buffer)) works.

Can you please help me understand what is happening here.


Solution

  • InputStreams have a hidden state: the position in the stream. When anyone reads from an InputStream the position changes. This means you can't read a stream twice, you have to create a new stream.

    ByteStreams.toByteArray has to read from the stream, so it changes the position.