AdSense

AdSense3

Monday, 3 November 2014

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

ConstructorDescription
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

MethodDescription
1) public synchronized void writeTo(OutputStream out) throws IOExceptionwrites the complete contents of this byte array output stream to the specified output stream.
2) public void write(byte b) throws IOExceptionwrites byte into this stream.
3) public void write(byte[] b) throws IOExceptionwrites 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 java.io.*;  
  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.   
  7.   ByteArrayOutputStream bout=new ByteArrayOutputStream();  
  8.   bout.write(139);  
  9.   bout.writeTo(fout1);  
  10.   bout.writeTo(fout2);  
  11.   
  12.   bout.flush();  
  13.   bout.close();//has no effect  
  14.   System.out.println("success...");  
  15.  }  
  16. }   
success...
Java ByteArrayOutputStream

No comments:

Post a Comment