How can I convert an OutputStream to a byte array? I have found that first I need to convert this OutputStream to a ByteArrayOutputStream. There is only write() method in this OutputStream class and I don't know what to do. Is there any idea?
The Java ByteArrayOutputStream class, java. io. ByteArrayOutputStream of the Java IO API enables you to capture data written to a stream in a byte array. You write your data to the ByteArrayOutputStream and when you are done you call the its toByteArray() method to obtain all the written data in a byte array.
1.2 OutputStream: OutputStream is an abstract class of Byte Stream that describes stream output and it is used for writing data to a file, image, audio, etc. Thus, OutputStream writes data to the destination one at a time.
Which of these method(s) is/are used for writing bytes to an outputstream? Explanation: write() and print() are the two methods of OutputStream that are used for printing the byte data.
Create a ByteArrayOutputStream
.
Grab its content by calling toByteArray()
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.writeTo(myOutputStream);
baos.toByteArray();
Reference
If the OutputStream
object supplied is not already a ByteArrayOutputStream
, one can wrap
it inside a delegate class that will "grab" the bytes supplied to the write()
methods, e.g.
public class DrainableOutputStream extends FilterOutputStream {
private final ByteArrayOutputStream buffer;
public DrainableOutputStream(OutputStream out) {
super(out);
this.buffer = new ByteArrayOutputStream();
}
@Override
public void write(byte b[]) throws IOException {
this.buffer.write(b);
super.write(b);
}
@Override
public void write(byte b[], int off, int len) throws IOException {
this.buffer.write(b, off, len);
super.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
this.buffer.write(b);
super.write(b);
}
public byte[] toByteArray() {
return this.buffer.toByteArray();
}
}
To reduce the overhead, the calls to super
in the above class can be omitted - e.g., if only the "conversion" to a byte array is desired.
A more detailed discussion can be found in another StackOverflow question.
You need to do 2 things
You could even extend it as mentioned here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With