ByteArrayInputStream in java

ByteArrayInputStream class is a subclass of InputStream abstract class. It creates an inputstream, which is used to read byte/bytes from its own internal buffer, which is initialized using a byte array.

  Java ByteArrayInputStream class contains an internal buffer which is used to read byte array as stream. In this stream, the data is read from a byte array.

  The buffer of ByteArrayInputStream automatically grows according to data.


Constructors of ByteArrayInputStream

Constructor Description
ByteArrayInputStream(byte[] data) Creates a new byte array input stream which uses data as its buffer array.
ByteArrayInputStream(byte[] data, int offset, int len) Creates a new byte array input stream which uses data as its buffer array that can read up to specified len bytes of data from an array.

Some Methods for reading ByteArrayInputStream

Access modifier of these methods is public.

Method Description
available() This method gives the remaining number of bytes available to read from this input stream.
read() This method reads one byte at a time from this input stream.
read(byte[]) This method reads a whole byte array at a time from this input stream.
close() This method closes this input stream and also frees any resources connected with this input stream.

Example : Reading the data form byte array using ByteArrayInputStream.


import java.io.ByteArrayInputStream;
import java.io.IOException;

public class ByteArrayInput {
    public static void main(String[] args) throws IOException {
        String content = "Java is multi-threaded programming language.";
        byte[] b = content.getBytes();//getting the byte array
        ByteArrayInputStream bais = new ByteArrayInputStream(b);

        //reading the content byte by byte
        while (true) {
            int i = bais.read();
            if (i == -1) {
                break;
            }
            System.out.print((char) i);
        }
        bais.close();
    }
}
Java is multi-threaded programming language.