I want to get the internal byte array from ByteArrayInputStream. I don't want to extends that class or write it into another byte array. Is there a utility class that help me do that?
Thanks,
I want to get the internal byte array from ByteArrayInputStream. I don't want to extends that class or write it into another byte array. Is there a utility class that help me do that?
Thanks,
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.
No. Extending the class is the only way (well, that and using reflection to bypass the field visibility, which absolutely NOT recommended).
The internal field is protected, so extending would be easy. If you really don't want to, reflection may be another way. This is not a great solution since it relies on internal workings of ByteArrayInputStream (such as knowing the field is called buf
). You have been warned.
ByteArrayInputStream bis = ...
Field f = ByteArrayInputStream.class.getDeclaredField("buf");
f.setAccessible(true);
byte[] buf = (byte[])f.get(bis);
No, access to the internal array is not provided except through the toByteArray() method, which makes a copy.