Java - ByteArrayInputStream Class



The Java ByteArrayInputStream class contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method.Following are the important points about ByteArrayInputStream −

  • Closing a ByteArrayInputStream has no effect.

  • The methods in this class can be called after the stream has been closed without generating an IOException.

Class declaration

Following is the declaration for java.io.ByteArrayInputStream class −

public class ByteArrayInputStream
   extends InputStream

Field

Following are the fields for java.io.ByteArrayInputStream class −

  • protected byte[] buf − This is an array of bytes that was provided by the creator of the stream.

  • protected int count − This is the index one greater than the last valid character in the input stream buffer.

  • protected int mark − This is the currently marked position in the stream.

  • protected int pos − This is the index of the next character to read from the input stream buffer.

Class constructors

Sr.No. Constructor & Description
1

ByteArrayInputStream(byte[] buf)

This creates a ByteArrayInputStream so that it uses buf as its buffer array.

2

ByteArrayInputStream(byte[] buf, int offset, int length)

This creates ByteArrayInputStream that uses buf as its buffer array.

Class methods

Sr.No. Method & Description
1 int available()

This method returns the number of remaining bytes that can be read (or skipped over) from this input stream.

2 void close()

Closing a ByteArrayInputStream has no effect.

3 void mark(int readAheadLimit)

This method set the current marked position in the stream.

4 boolean markSupported()

This method tests if this InputStream supports mark/reset.

5 int read()

This method reads the next byte of data from this input stream.

6 int read(byte[] b, int off, int len)

This method reads up to len bytes of data into an array of bytes from this input stream.

7 void reset()

This method resets the buffer to the marked position.

8 long skip(long n)

This method skips n bytes of input from this input stream.

Methods inherited

This class inherits methods from the following classes −

  • java.io.InputStream
  • java.io.Object

Example - Using ByteArrayInputStream available() method

The following example shows the usage of Java ByteArrayInputStream available() method.

ByteArrayInputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayInputStream;

public class ByteArrayInputStreamDemo {
   public static void main(String[] args) {
      // Create a byte array
      byte[] data = {65, 66, 67, 68, 69}; // Corresponds to 'A', 'B', 'C', 'D', 'E'

      // Create a ByteArrayInputStream using the byte array
      ByteArrayInputStream inputStream = new ByteArrayInputStream(data);

      // Check the number of bytes available initially
      System.out.println("Bytes available at the start: " + inputStream.available());

      // Read the first byte
      int firstByte = inputStream.read();
      System.out.println("Read byte: " + (char) firstByte);

      // Check the number of bytes available after reading one byte
      System.out.println("Bytes available after reading one byte: " + inputStream.available());

      // Read all remaining bytes
      while (inputStream.available() > 0) {
         int byteData = inputStream.read();
         System.out.println("Read byte: " + (char) byteData);
      }

      // Check the number of bytes available at the end
      System.out.println("Bytes available at the end: " + inputStream.available());
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Bytes available at the start: 5
Read byte: A
Bytes available after reading one byte: 4
Read byte: B
Read byte: C
Read byte: D
Read byte: E
Bytes available at the end: 0

Explanation

  • Initialization− A ByteArrayInputStream is created using a byte array that contains values representing ASCII characters ('A', 'B', 'C', 'D', 'E').

  • Initial Available Bytes− The available() method is called at the start, returning the total number of bytes in the stream (5 in this case).

  • After Reading− When a byte is read using the read() method, the available bytes decrease by 1.

  • While Loop− The program uses a loop to read and print all remaining bytes while available() indicates more bytes are left in the stream.

  • Final Check− At the end, when all bytes have been read, available() returns 0.

Example - Using ByteArrayInputStream close() method

The following example shows the usage of Java ByteArrayInputStream close() method.

ByteArrayInputStreamDemo.java

package com.tutorialspoint;

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

public class ByteArrayInputStreamDemo {
   public static void main(String[] args) {
      // Create a byte array
      byte[] data = {72, 101, 108, 108, 111}; // Corresponds to 'H', 'e', 'l', 'l', 'o'

      // Create a ByteArrayInputStream
      ByteArrayInputStream inputStream = new ByteArrayInputStream(data);

      // Read and print data from the stream
      try {
         int byteData;
         System.out.println("Reading bytes from ByteArrayInputStream:");
         while ((byteData = inputStream.read()) != -1) {
            System.out.print((char) byteData);
         }
         System.out.println();

         // Close the ByteArrayInputStream
         inputStream.close();
         System.out.println("Stream closed successfully.");
      } catch (IOException e) {
         System.err.println("An I/O error occurred: " + e.getMessage());
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Reading bytes from ByteArrayInputStream:
Hello
Stream closed successfully.

Explanation

  • Initialization− A ByteArrayInputStream is created using a byte array that represents the string "Hello".

  • Reading Data− The read() method is used to read bytes from the stream one at a time until the end of the stream is reached.

  • Closing the Stream− The close() method is called to close the stream. For ByteArrayInputStream, this is not strictly necessary because no resources are allocated outside of the memory. However, calling close() is consistent with standard Java I/O practices.

Example - Using ByteArrayInputStream mark() method

The following example shows the usage of Java ByteArrayInputStream mark() method.

ByteArrayInputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayInputStream;

public class ByteArrayInputStreamMarkExample {
   public static void main(String[] args) {
      // Create a byte array
      byte[] data = {65, 66, 67, 68, 69}; // Corresponds to 'A', 'B', 'C', 'D', 'E'

      // Create a ByteArrayInputStream
      ByteArrayInputStream inputStream = new ByteArrayInputStream(data);

      // Read and print the first two bytes
      System.out.println("Reading first two bytes:");
      System.out.println((char) inputStream.read()); // Read 'A'
      System.out.println((char) inputStream.read()); // Read 'B'

      // Mark the current position in the stream
      inputStream.mark(0); // Mark at position 2 (after 'B')
      System.out.println("Marked the current position.");

      // Read the next two bytes
      System.out.println("Reading next two bytes:");
      System.out.println((char) inputStream.read()); // Read 'C'
      System.out.println((char) inputStream.read()); // Read 'D'

      // Reset the stream to the marked position
      inputStream.reset();
      System.out.println("Stream reset to the marked position.");

      // Read again from the marked position
      System.out.println("Reading bytes again from the marked position:");
      System.out.println((char) inputStream.read()); // Read 'C' again
      System.out.println((char) inputStream.read()); // Read 'D' again

      // Read the last byte
      System.out.println((char) inputStream.read()); // Read 'E'
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Reading first two bytes:
A
B
Marked the current position.
Reading next two bytes:
C
D
Stream reset to the marked position.
Reading bytes again from the marked position:
C
D
E

Explanation

  • Initialization− A ByteArrayInputStream is created using a byte array containing the ASCII values for 'A', 'B', 'C', 'D', and 'E'.

  • Marking the Stream− After reading the first two bytes ('A' and 'B'), the mark(0) method is called to mark the current position in the stream. Here, readAheadLimit is ignored for ByteArrayInputStream.

  • Resetting the Stream− After reading the next two bytes ('C' and 'D'), the reset() method is called. This resets the stream back to the position marked by mark() (position 2, after 'B').

  • Reading Again− After resetting, the stream reads 'C' and 'D' again, demonstrating that the stream has returned to the marked position.

  • Final Byte− The program continues to read the last byte ('E') to complete the reading process.

Advertisements