How to use ByteArrayOutputStream and DataOutputStream simultaneously in Java?
Use the former case - wrap DataOutputStream
around the ByteArrayOutputStream
. Just make sure you save the reference to the ByteArrayOutputStream
. When you are finished, close() or at least flush() the DataOutputStream
and then use the toByteArray method of the ByteArrayOutputStream
.
You could use a stream approach if you connect your outputstream to an inputstream through a PipedInputStream
/PipetOutputStream
. Then you will consume the data from the inputstream.
Anyway if what you need to do is simple and doesn't not require a stream approach I would use a java.nio.ByteBuffer
on which you have
put(byte[] src)
for yourbyte[]
putInt(int value)
- and
byte[] array()
to get the content
Could you make a variable to hold on to the ByteArrayOutputStream and pass it into the DataOutputStream.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(1);
byte[] result = dos.toByteArray();
Like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream w = new DataOutputStream(baos);
w.writeInt(100);
w.write(byteArray);
w.flush();
byte[] result = baos.toByteArray();
Actually your second version will not work at all. DataOutputStream
requires an actual target stream in which to write the data. You can't do new DataOutputStream()
. There isn't actually any constructor like that.