The class ByteArrayOutputStream does just the opposite functionality of ByteArrayInputStream.

The ByteArrayInputStream reads data from the array and now the ByteArrayOutputStream writes the data to the byte array. All the characters of the array can be written or a few also. In the following program, both functionalities are illustrated.

public class BAODemo
  public static void main(String args[]) throws IOException
  {                             // to write the whole byte array
    byte alphabets[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G'  };
    ByteArrayOutputStream bao1 = new ByteArrayOutputStream();
    System.out.println("Getting all the bytes from the stream: " + bao1.toString());
                               // to write a part of byte array
    ByteArrayOutputStream bao2 = new ByteArrayOutputStream();
    bao2.write( alphabets, 2, 4 );
    System.out.println("Getting 4 bytes starting from 2: " + bao2.toString());



In the above statement, complete byte array alphabets is written to the ByteArrayOutputStream object, bao1.

bao2.write( alphabets, 2, 4 );

To ByteArrayOutputStream object, bao2, a part of the array is written; four characters starting from second.

It is a good practice to close the streams when the job is over as with bao1.close().

Pass your suggestions or comments on this tutorial.

Leave a Comment

Your email address will not be published.