Easy Tutorial
❮ String Uppercase Thread Interrupt ❯

Java ByteArrayInputStream Class

Java Streams


A ByteArrayInputStream creates a byte array buffer in memory and stores data read from the input stream in this byte array buffer. There are several ways to create a ByteArrayInputStream object.

Creating by accepting a byte array as a parameter:

ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);

Another way to create is by accepting a byte array and two integer variables off and len, where off represents the first byte to read and len represents the length of the bytes to read.

ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a, 
                                                       int off, 
                                                       int len)

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

No. Method Description
1 public int read() <br> Reads the next byte of data from this input stream.
2 public int read(byte[] r, int off, int len) <br> Reads up to len bytes of data from this input stream into a byte array.
3 public int available() <br> Returns the number of bytes that can be read from this input stream without blocking.
4 public void mark(int read) <br> Sets the current marked position in the stream.
5 public long skip(long n) <br> Skips over and discards n bytes of data from this input stream.

Example

The following example demonstrates the use of ByteArrayInputStream and ByteArrayOutputStream:

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 Uppercase Thread Interrupt ❯