Java ByteArrayOutputStream Class
A byte array output stream creates a byte array buffer in memory, and all data sent to the output stream is stored in this byte array buffer. There are several ways to create a ByteArrayOutputStream object.
The following constructor creates a 32-byte (default size) buffer.
OutputStream bOut = new ByteArrayOutputStream();
Another constructor creates a buffer of sizeabytes.
OutputStream bOut = new ByteArrayOutputStream(int a)
After successfully creating a ByteArrayOutputStream object, you can refer to the following list of methods to perform write operations or other operations on the stream.
| No. | Method Description |
|---|---|
| 1 |
public void reset() This byte array output stream's countfield is reset to zero, thereby discarding all data output currently accumulated in the output stream. |
| 2 |
public byte[] toByteArray() Creates a newly allocated byte array. The size of the array is the size of the current output stream, and its content is a copy of the current output stream. |
| 3 |
public String toString() Converts the contents of the buffer to a string, converting bytes to characters according to the platform's default character encoding. |
| 4 |
public void write(int w) Writes the specified byte to this byte array output stream. |
| 5 |
public void write(byte []b, int off, int len) In the specified byte array offstarting from the offsetlenthe bytes are written to this byte array output stream. |
| 6 |
public void writeTo(OutputStream outSt) Writes the entire contents of this byte array output stream to the specified output stream argument. |
Example
The following example demonstrates the use of ByteArrayInputStream and ByteArrayOutputStream:
Example
import java.io.*;
public class ByteStreamTest {
public static void main(String args[])throws IOException {
ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
while( bOutput.size()!= 10 ) {
//Get user input
bOutput.write(System.in.read());
}
byte b [] = bOutput.toByteArray();
System.out.println("Print the content");
for(int x= 0 ; x < b.length; x++) {
//Print characters
System.out.print((char)b[x] + " ");
}
System.out.println(" ");
int c;
ByteArrayInputStream bInput = new ByteArrayInputStream(b);
System.out.println("Converting characters to Upper case " );
for(int y = 0 ; y < 1; y++ ) {
while(( c= bInput.read())!= -1) {
System.out.println(Character.toUpperCase((char)c));
}
bInput.reset();
}
}
}
The result of compiling and running the above example is as follows:
asdfghjkly Print the content a s d f g h j k l y Converting characters to Upper case A S D F G H J K L Y
Other Extensions
Java Stream