I am trying to convert an OutputStream
to a ByteArrayOutput
Stream. I was unable to find any clear simple answers on how to do this. This question wa
You can use toByteArray
function on the output stream you have.That's is let say you have outputStream buffer So you can do buffer.toByteArray
.
For more you can look at the answer of Convert InputStream to byte array in Java .
There are multiple possible scenarios:
a) You have a ByteArrayOutputStream, but it was declared as OutputStream. Then you can do a cast like this:
void doSomething(OutputStream os)
{
// fails with ClassCastException if it is not a BOS
ByteArrayOutputStream bos = (ByteArrayOutputStream)os;
...
b) if you have any other type of output stream, it does not really make sense to convert it to a BOS. (You typically want to cast it, because you want to access the result array). So in this case you simple set up a new stream and use it.
void doSomething(OutputStream os)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(something);
bos.close();
byte[] arr = bos.toByteArray();
// what do you want to do?
os.write(arr); // or: bos.writeTo(os);
...
c) If you have written something to any kind of OutputStream (which you do not know what it is, for example because you get it from a servlet), there is no way to get that information back. You must not write something you need later. A solution is the answer b) where you write it in your own stream, and then you can use the array for your own purpose as well as writing it to the actual output stream.
Keep in mind ByteArrayOutputStreams keep all Data in Memory.
You could use the writeTo
method of ByteArrayOutputStream
.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[8];
bos.write(bytes);
bos.writeTo(oos);
You can create an instance of ByteArrayOutputStream
. You then need to write the data to this ByteOutputStream
instance and then using the writeTo
method, which accepts an OutputStream
, you can enable the ByteArrayOutputStream
to write the output, to the instance of OutputStream
which you passed as the argument.
Hope it works!