ByteArrayOutputStream in java

ByteArrayOutputStream class is a subclass of OutputStream abstract class. It is used to write content of a byte array to the output stream by performing two steps in sequence -

  1) First, it writes contents of a byte array to its own internal buffer.

  2) Next, it writes the bytes out of its internal buffer to a file, through an output stream.

  3) Java ByteArrayOutputStream class is also used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later.


Java ByteArrayOutputStream class constructors

Constructor Description
ByteArrayOutputStream() Creates a new byte array output stream with the initial capacity of 32 bytes, though its size increases if necessary.
ByteArrayOutputStream(int size) Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

Methods for writing bytes using ByteArrayOutputStream

Some methods that we generally use while working with ByteArrayOutputStream are shown in the table below :

Methods Description
flush() This method flushes any buffered data to be written out of this output stream.
size() This method returns the current size of the buffer of ByteArrayOutputStream.
write(int b) This method writes one byte at a time to this output stream.
write(byte[]) This method writes a whole byte array at a time to this input stream.
writeTo(OutputStream out) This method writes the content of ByteArrayOutputStream to the output stream passed to it in the parameters.
close() This method closes this outut stream and also frees any resources connected with this output stream.

Example : using ByteArrayOutputStream


import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ByteArrayOutput {
    public static void main(String[] args) throws IOException {
        String content = "Java is most popular language in the world.";
        byte b[] = content.getBytes();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        System.out.println("intial size of the stream is : " + baos.size());

        for (byte bb : b) {
            baos.write(bb);
        }

        System.out.println("size of the stream after writing the content : " + baos.size());
        System.out.println("Now going to write the content to file ");
        FileOutputStream fos = new FileOutputStream("newfile.txt");
        baos.writeTo(fos);
        System.out.println("done");
        fos.close();
        baos.close();


    }
}
intial size of the stream is : 0
size of the stream after writing the content : 43
Now going to write the content to file 
done