Easy Tutorial
❮ String Optimization Number Max ❯

Java ByteArrayOutputStream Class

Java Streams


The ByteArrayOutputStream class creates an in-memory byte array buffer, where 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 buffer of 32 bytes (default size).

OutputStream bOut = new ByteArrayOutputStream();

Another constructor creates a buffer of size a bytes.

OutputStream bOut = new ByteArrayOutputStream(int a)

After successfully creating a ByteArrayOutputStream object, you can refer to the methods in the following list to write to the stream or perform other operations.

No. Method Description
1 public void reset() <br>Resets the count field of this byte array output stream to zero, thereby discarding all currently accumulated data output.
2 public byte[] toByteArray() <br>Creates a newly allocated byte array. Its size is the current size of the output stream, and the contents are a copy of the output stream.
3 public String toString() <br>Converts the buffer's contents into a string, translating bytes into characters according to the platform's default character encoding.
4 public void write(int w) <br>Writes the specified byte to this byte array output stream.
5 public void write(byte []b, int off, int len) <br>Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
6 public void writeTo(OutputStream outSt) <br>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 above example compiles and runs with the following result:

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

Java Streams

❮ String Optimization Number Max ❯