Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert outputStream to a byte array?

Tags:

java

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?

like image 614
hellzone Avatar asked Apr 18 '14 12:04

hellzone


People also ask

How do you get ByteArrayOutputStream bytes?

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.

What is an OutputStream?

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 is used for writing bytes to an OutputStream?

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.


3 Answers

Create a ByteArrayOutputStream.

Grab its content by calling toByteArray()

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
baos.writeTo(myOutputStream); 
baos.toByteArray();

Reference

like image 176
washcloth Avatar answered Oct 04 '22 07:10

washcloth


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.

like image 27
PNS Avatar answered Oct 04 '22 05:10

PNS


You need to do 2 things

  • Using ByteArrayOutputStream write to it
  • Using toByteArray(), you will get the contents as byte[]

You could even extend it as mentioned here

like image 40
John Avatar answered Oct 04 '22 06:10

John