ByteArrayOutputStream Class In Java
ByteArrayOutputStream
The ByteArrayOutputStream class creates a buffer inside the memory and all the data sent to the stream is stored in the buffer and the buffer of ByteArrayOutputStream automatically grows according to data.
ByteArrayOutputStream class is mainly used to write the data into multiple files. In this stream, the data is written into a byte array, which can be written to multiple streams. It holds a copy of data and forward it to the multiple streams.
Constructors of ByteArrayOutputStream class
ByteArrayOutputStream()
It is used to create a new byte array output stream with the initial capacity of 32 bytes, though its size increases, if necessary.
ByteArrayOutputStream(int size)
It is used to create a new byte array output stream, with a buffer capacity of the specified size, in bytes.
Methods of ByteArrayOutputStream class
public synchronized void writeTo(OutputStream out) throws IOException
This method is used to write the complete contents of this byte array output stream to the specified output stream.
public void write(byte b) throws IOException
This method is used to write byte into this stream.
public void write(byte[] b) throws IOException
This method is used to write byte array into this stream.
public void flush()
This method is used to flushe this stream.
public void close()
This method has no effect, it doesn't close the bytearrayoutputstream.
Let's see an example, given below.
Code
- import java.io.*;
- public class FileHandlingExample {
- public static void main(String args[]) throws Exception {
- FileOutputStream fos1 = new FileOutputStream("file1.txt");
- FileOutputStream fos2 = new FileOutputStream("file2.txt");
- ByteArrayOutputStream b = new ByteArrayOutputStream();
- b.write(999);
- b.writeTo(fos1);
- b.writeTo(fos2);
- b.flush();
- b.close();
- System.out.println("Run successfully...");
- }
- }
Output
In the above example, we create ByteArrayOutputStream class that writes data into 2 files.
Summary
Thus, we learnt that the ByteArrayOutputStream class creates a buffer inside the memory and all the data sent to the stream is stored in the buffer in Java and also learnt its important methods and constructors.