ByteArrayOutputStream

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.

import java.io.*;
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();
    bao1.write(alphabets);
    System.out.println("Getting all the bytes from the stream: " + bao1.toString());
    bao1.close();  
                               // 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());
    bao2.close();
  }
}

image

bao1.write(alphabets);

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.