Get internal byte array from ByteArrayInputStream

You can not get access to the same byte array, but you can easily copy the contents of the stream:

public byte[] read(ByteArrayInputStream bais) {
     byte[] array = new byte[bais.available()];
     bais.read(array);

     return array;
}

With the library Apache COmmons IO (http://commons.apache.org/io/) you can use the IOUtils.toByteArray(java.io.InputStream input)

Edit : ok, I didn't understood the question... no copy... Maybe something like :

byte[] buf = new byte[n];
ByteArrayInputStream input = new ByteArrayInputStream(buf);

will allow you to keep a reference to the buffer used by the input stream


Extend ByteArrayInputStream, then you have access to the protected fields. It's the way to do it. Constructors are provided to take the byte array from an argument.

However, you may find the decorator pattern more helpful.

Tags:

Java