All for Joomla All for Webmasters

Java ByteArrayOutputStream class

Java ByteArrayOutputStream class is used to write data into multiple files. In this stream, the data is written into a byte array that can be written to multiple stream.

The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.

The buffer of ByteArrayOutputStream automatically grows according to data.

Closing the ByteArrayOutputStream has no effect.

Constructors of ByteArrayOutputStream class

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 of ByteArrayOutputStream class

Method Description
1) public synchronized void writeTo(OutputStream out) throws IOException writes the complete contents of this byte array output stream to the specified output stream.
2) public void write(byte b) throws IOException writes byte into this stream.
3) public void write(byte[] b) throws IOException writes byte array into this stream.
4) public void flush() flushes this stream.
5) public void close() has no affect, it doesn’t closes the bytearrayoutputstream.

Java ByteArrayOutputStream Example

Let’s see a simple example of java ByteArrayOutputStream class to write data into 2 files.

  1. import*;
  2. class S{
  3.  public static void main(String args[])throws Exception{
  4.   FileOutputStream fout1=new FileOutputStream(“f1.txt”);
  5.   FileOutputStream fout2=new FileOutputStream(“f2.txt”);
  6.   ByteArrayOutputStream bout=new ByteArrayOutputStream();
  7.   bout.write(139);
  8.   bout.writeTo(fout1);
  9.   bout.writeTo(fout2);
  10.   bout.flush();
  11.   bout.close();//has no effect
  12.   System.out.println(“success…”);
  13.  }
  14. }

submit to reddit

Leave a Reply