Java ByteArrayOutputStream Class


In Java, the ByteArrayOutputStream class stream creates a buffer in memory. All the data sent to the stream to stored in the buffer.

Syntax:

 public class ByteArrayOutputStream extends OutputStream

ByteArrayOutputStream Class Constructors

S.No Constructor Description
1 ByteArrayOutputStream() It creates a ByteArrayOutput stream having buffer of 32 bytes. Its size may be increase if necessary.
2 ByteArrayOutputStream(int size) It creates a ByteArrayOutput stream with a buffer of the given size.

ByteArrayOutputStream Class Methods

1 byte[] toByteArray() This method is used to create a newly allocated byte array.
2 public String toString() This method is used to convert buffer content into a string.
3 void write(int a) It is used to writes the specified array to the output stream.
4 void write(byte[] a, int off, int len This method is used to writes len number of bytes starting from offset off to the byte array output stream.
5 public void writeTo(OutputStream ot) It is used to writes the entire content of this Stream to the specified output stream.
6 void close() This method is used for closing a ByteArrayOutputStream.
7 void reset() This method is used to reset the number of valid bytes of the byte array output stream to zero.

Example:

import java.io.*;
public class ByteArrayOutputStreamDemo{
    public static void main(String args[]) throws IOException{  
		ByteArrayOutputStream baout = new ByteArrayOutputStream();
		String s = "Welcome to Onlinetpoint";
		byte bu[] = s.getBytes();
		baout.write(bu);
		System.out.println(baout.toString());
		OutputStream outs = new FileOutputStream("Out.txt");
		baout.writeTo(outs);
		outs.close();
		System.out.println("Success");
		baout.reset();
    }
} 

Output

Success 

Out.txt

Welcome to Onlinetpoint



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.