Java - ByteArrayInputStream read(byte[] b, int off, int len) method



Description

The Java ByteArrayInputStream read(byte[] b, int off, int len) method is used to read up to len bytes of data from the input stream into a specified portion of a byte array (b). The data starts being written at index off in the array. The method returns the number of bytes read, or -1 if the end of the stream has been reached.

Declaration

Following is the declaration for java.io.ByteArrayInputStream.read(byte[] b, int off, int len) method −

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

Parameters

  • b − data is read into this buffer

  • off − Offset to start at destination array b

  • len − maximum number of bytes read

Return Value

Number of bytes read into the buffer. Returns -1 if the stream has reached it's end.

Exception

  • NullPointerException − If b is null.

  • IndexOutOfBoundsException − If len is greater than input stream's length after offset, off is negative, or len is negative.

Example - Using ByteArrayInputStream read(byte[] b, int off, int len) method

The following example shows the usage of Java ByteArrayInputStream read(byte[] b, int off, int len) method. We've created a variable buf as byte[] and initialized with few bytes. We've created a ByteArrayInputStream reference and then initialized it with buf variable. We've created a buffer of 4 bytes and read the byte array stream into the buffer using read() method. Then buffer is iterated to print the bytes read.

ByteArrayInputStreamDemo.java

package com.tutorialspoint;

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

public class ByteArrayInputStreamDemo {
   public static void main(String[] args) throws IOException {
      byte[] buf = {65, 66, 67, 68, 69};
      ByteArrayInputStream bais = null;
      
      try {
         // create new byte array input stream
         bais = new ByteArrayInputStream(buf);
      
         // create buffer
         byte[] b = new byte[4];
         int num = bais.read(b, 2, 2);
         
         // number of bytes read
         System.out.println("Bytes read: "+num);
         
         // for each byte in a buffer
         for (byte s :b) {
         
            // covert byte to char
            char c = (char)s;
            
            // prints byte
            System.out.print(s);
            
            if(s == 0)
               
               // if byte is 0
               System.out.println(": Null");
            else
               
               // if byte is not 0
               System.out.println(": "+c);
         }
         
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(bais!=null)
            bais.close();
      }   
   }
}

Output

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

Bytes read: 2
0: Null
0: Null
65: A
66: B

Example - Using ByteArrayInputStream read(byte[] b, int off, int len) method

The following example shows the usage of Java ByteArrayInputStream read(byte[] b, int off, int len) method. We've created a variable buf as byte[] and initialized with empty array. We've created a ByteArrayInputStream reference and then initialized it with buf variable. We've created a buffer of 4 bytes and read the byte array stream into the buffer using read() method. In if loop, we're checking if stream contains any byte using available() method and then its result is printed.

ByteArrayInputStreamDemo.java

package com.tutorialspoint;

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

public class ByteArrayInputStreamDemo {
   public static void main(String[] args) throws IOException {
      byte[] buf = {};
      ByteArrayInputStream bais = null;
      
      try {
         // create new byte array input stream
         bais = new ByteArrayInputStream(buf);
         
         // create buffer
         byte[] b = new byte[4];
         int num = bais.read(b, 2, 2);
         
         // number of bytes read
         System.out.println("Bytes read: "+num);
         int value = 0;
         // read the stream
         if((value = bais.read())!=-1) {
            // convert byte to character
            char c = (char)value;
            
            // print
            System.out.println("byte :"+value+"; char : "+ c);
         }else{
            System.out.print("byte stream is empty");
         } 
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(bais!=null)
            bais.close();
      }
   }
}

Output

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

Bytes read: -1
byte stream is empty

Example - Using ByteArrayInputStream read(byte[] b, int off, int len) method

The following example shows the usage of Java ByteArrayInputStream read(byte[] b, int off, int len) method.

ByteArrayInputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayInputStream;

public class ByteArrayInputStreamDemo {
   public static void main(String[] args) {
      // Create a byte array as the data source
      byte[] data = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}; // "Hello World"

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

      // Create a buffer to store the read data
      byte[] buffer = new byte[6]; // Buffer size of 6 bytes

      // Read data into the buffer starting at an offset of 2
      int bytesRead = inputStream.read(buffer, 2, 4); // Read up to 4 bytes into buffer[2] to buffer[5]

      // Print the number of bytes read
      System.out.println("Bytes read: " + bytesRead);

      // Print the contents of the buffer
      System.out.println("Buffer contents (ASCII values):");
      for (byte b : buffer) {
         System.out.print(b + " "); // Print the byte value
      }

      // Convert the buffer to a string to demonstrate the readable part
      System.out.println("\nBuffer contents (characters):");
      System.out.println(new String(buffer)); // Convert buffer to a string
   }
}

Output

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

Bytes read: 4
Buffer contents (ASCII values):
0 0 72 101 108 108 
Buffer contents (characters):
Hell

Explanation

  • Initialization

    • A ByteArrayInputStream is created using a byte array containing the ASCII values for "Hello World".

    • A buffer of size 6 bytes is created to store the data read from the stream.

  • Reading Data

    • The read(byte[] b, int off, int len) method is called with off = 2 and len = 4. This means up to 4 bytes will be read from the stream and stored starting at index 2 of the buffer.

    • The method returns the number of bytes actually read, which might be less than len if fewer bytes are available.

  • Printing the Results

    • The program prints the number of bytes read and the contents of the buffer.

    • The buffer is partially filled with the bytes read, starting at index 2, while the rest of the buffer remains uninitialized (0).

  • Converting to Characters

    • The buffer is converted to a string to display the readable portion of the data.

Key Points

  • Parameters

    • b− The destination byte array to hold the data read from the stream.

    • off− The starting offset in the array where the data will be stored.

    • len− The maximum number of bytes to read.

  • Return Value

    • The method returns the number of bytes read. If no bytes are available and the end of the stream is reached, it returns -1.

  • Buffer Contents

    • Only the specified portion of the buffer (starting from off to off + len) is filled with data. The rest remains unmodified.

  • Handling End of Stream

    • If the stream has fewer than len bytes remaining, only the available bytes are read, and the method returns the actual number of bytes read.

java_bytearrayinputstream.htm
Advertisements