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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.