Java-ByteArrayOutputStream

ByteArrayOutputStream

The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to one or more stream is stored in the buffer. The buffer of ByteArrayOutputStream automatically grows according to data. In this stream, the data is written into a byte array.

You write your data to the ByteArrayOutputStream and when you are done you call the ByteArrayOutputStream’s method toByteArray( ) to obtain all the written data in a byte array. Being a subclass of OutputStream the ByteArrayOutputStream also has a close( ) method. But calling the close() method has no effect on the ByteArrayOutputStream.

ByteArrayOutputStream Constructors

Constructors Description
ByteArrayOutputStream() Creates a new byte array output stream.
ByteArrayOutputStream(int size) Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

ByteArrayOutputStream Methods

Method Description
byte[] toByteArray() Creates a newly allocated Byte array. Its size would be the current size of the output stream and the contents of the buffer will be copied into it. Returns the current contents of the output stream as a byte array.
String toString() Converts the buffer’s content into a string. Translation will be done according to the default character encoding. Returns the String translated from the buffer’s content.
String toString(String charsetName) Converts the buffer’s contents into a string by decoding the bytes using the specified.
void reset() Resets the number of valid bytes of the byte array output stream to zero, so all the accumulated output in the stream will be discarded.
void write(int b) Writes the specified byte to this byte array output stream.
void write(byte[] b, int off, int len) Writes ‘len‘ bytes from the specified byte array starting at offset ‘off‘ to this byte array output stream.
void writeTo(OutputStream out) Writes the entire content of this Stream to the specified stream argument.

Program

Program Source

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

public class Javaapp {
    
    public static void main(String[] args) throws IOException {
        
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        FileOutputStream fo = new FileOutputStream("data.da");
        System.out.println("bos Size : "+bos.size());
        
        byte by1[] = {10,20,30,40,50};
        bos.write(by1);
        System.out.println("bos Size : "+bos.size());
        
        byte by2[] = {40,50,60,70,80,90,100};
        bos.write(by2, 2, 5);
        System.out.println("bos Size : "+bos.size());
        
        bos.writeTo(fo);
        fo.close();  
    }
}

Leave a Comment