Java Bytearrayoutputstream Class

The Java ByteArrayOutputStream class is utilized for writing shared data into various files. Within this stream, information is written into a byte array that can be subsequently written into multiple streams.

The ByteArrayOutputStream stores a duplicate of information and transmits it to various streams.

The size of the buffer in ByteArrayOutputStream expands dynamically in response to the amount of data being written into it.

Java ByteArrayOutputStream class declaration

Let's examine the declaration of the Java.io.ByteArrayOutputStream class:

Example

public class ByteArrayOutputStream extends OutputStream

Java ByteArrayOutputStream class constructors

Constructor Description
ByteArrayOutputStream() Creates a new byte array outputstreamwith 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.

Java ByteArrayOutputStream class methods

Method Description
int size() It is used to returns the current size of a buffer.
byte[] toByteArray() It is used to create a newly allocated byte array.
String toString() It is used for converting the content into astringdecoding bytes using a platform default character set.
String toString(String charsetName) It is used for converting the content into a string decoding bytes using a specified charsetName.
void write(int b) It is used for writing the byte specified to the byte array output stream.
void write(byte[] b, int off, int len It is used for writinglenbytes from specified byte array starting from the offsetoffto the byte array output stream.
void writeTo(OutputStream out) It is used for writing the complete content of a byte array output stream to the specified output stream.
void reset() It is used to reset the count field of a byte array output stream to zero value.
void close() It is used to close the ByteArrayOutputStream.

Example of Java ByteArrayOutputStream

Consider the following basic demonstration of utilizing the Java ByteArrayOutputStream class to write shared data to two files named f1.txt and f2.txt.

Example

package com.example;

import java.io.*;

public class DataStreamExample {

public static void main(String args[])throws Exception{  

	  FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");  

	  FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");  

	  

	  ByteArrayOutputStream bout=new ByteArrayOutputStream();  

	  bout.write(65);  

	  bout.writeTo(fout1);  

	  bout.writeTo(fout2);  

	  

	  bout.flush();  

	  bout.close();//has no effect  

	  System.out.println("Success...");  

	 }  

	}

Output:

Output

Success...

f1.txt:

f2.txt:

Input Required

This code uses input(). Please provide values below: