Java Bytearrayinputstream Class

The ByteArrayInputStream is a combination of two terms: ByteArray and InputStream. Its primary purpose is to enable the reading of a byte array as an input stream.

The Java ByteArrayInputStream class features an internal buffer that functions to read a byte array as a stream. This stream is responsible for extracting data from a byte array.

The capacity of the buffer in a ByteArrayInputStream expands dynamically based on the amount of data being written into it.

Java ByteArrayInputStream class declaration

Now, let's examine the declaration of the Java.io.ByteArrayInputStream class:

Example

public class ByteArrayInputStream extends InputStream

Java ByteArrayInputStream class constructors

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

Java ByteArrayInputStream class methods

Methods Description
int available() It is used to return the number of remaining bytes that can be read from the input stream.
int read() It is used to read the next byte of data from the input stream.
int read(byte[] ary, int off, int len) It is used to read up to len bytes of data from an array of bytes in the input stream.
boolean markSupported() It is used to test the input stream for mark and reset method.
long skip(long x) It is used to skip the x bytes of input from the input stream.
void mark(int readAheadLimit) It is used to set the current marked position in the stream.
void reset() It is used to reset the buffer of a byte array.
void close() It is used for closing a ByteArrayInputStream.

Example of Java ByteArrayInputStream

Below is a straightforward illustration demonstrating the usage of the Java ByteArrayInputStream class to interpret a byte array as an input stream.

Example

package com.example;

import java.io.*;

public class ReadExample {

  public static void main(String[] args) throws IOException {

    byte[] buf = { 35, 36, 37, 38 };

    // Create the new byte array input stream

    ByteArrayInputStream byt = new ByteArrayInputStream(buf);

    int k = 0;

    while ((k = byt.read()) != -1) {

      //Conversion of a byte into character

      char ch = (char) k;

      System.out.println("ASCII value of Character is:" + k + "; Special character is: " + ch);

    }

  }

}

Output:

Output

ASCII value of Character is:35; Special character is: #

ASCII value of Character is:36; Special character is: $

ASCII value of Character is:37; Special character is: %

ASCII value of Character is:38; Special character is: &

Input Required

This code uses input(). Please provide values below: