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



Description

The Java InputStream read(byte[] b, int off, int len) method reads up to len bytes into a byte array, starting from a given offset (off) in the array. Returns the number of bytes actually read (-1 if EOF is reached).

Declaration

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

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

Parameters

  • b − The destination byte array.

  • off − The start offset in array b at which the data is written.

  • len − The number of bytes to read.

Return Value

The method returns the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

Exception

  • IOException − If an I/O error occurs.

  • NullPointerException − If b is null.

  • IndexOutOfBoundsException − If off is negative, len is negative, or len is greater than b.length - off.

Example - Usage of InputStream read(byte[] b, int off, int len) method

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

InputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.InputStream;

public class InputStreamDemo {
   public static void main(String[] args) throws Exception {
      InputStream is = null;
      byte[] buffer = new byte[5];
      char c;
      
      try {
         // new input stream created
         is = new FileInputStream("test.txt");
         
         System.out.println("Characters printed:");
         
         // read stream data into buffer
         is.read(buffer, 2, 3);
         
         // for each byte in the buffer
         for(byte b:buffer) {
         
            // convert byte to character
            if(b == 0)
               
               // if b is empty
               c = '-';
            else
               
               // if b is read
               c = (char)b;
            
            // prints character
            System.out.print(c);
         }
         
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases system resources associated with this stream
         if(is!=null)
            is.close();
      }
   }
}

Output(Assuming test.txt contains "ABCDE")

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

Characters printed:
--ABC

Example - Reading a File into a Portion of a Byte Array Using FileInputStream

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

InputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamDemo {
   public static void main(String[] args) {
      try (InputStream inputStream = new FileInputStream("example.txt")) {
         byte[] buffer = new byte[10]; // Buffer of size 10
         int bytesRead = inputStream.read(buffer, 2, 5); // Read 5 bytes starting from index 2

         if (bytesRead != -1) {
            System.out.println("Bytes read: " + bytesRead);
            System.out.println("Buffer content: " + new String(buffer, 0, buffer.length)); // Print entire buffer
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output(if example.txt contains "HelloWorld")

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

Bytes read: 5
Buffer content:   Hello

Explanation

  • Uses FileInputStream to read from "example.txt".

  • Reads 5 bytes into buffer, starting at index 2.

  • The first two positions in buffer remain empty (\0).

  • Converts the entire buffer to a string and prints it.

Example - Reading a File in Chunks Using BufferedInputStream

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

InputStreamDemo.java

package com.tutorialspoint;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamDemo {
   public static void main(String[] args) {
      try (InputStream inputStream = new BufferedInputStream(new FileInputStream("example.txt"))) {
         byte[] buffer = new byte[10]; // Buffer size 10
         int bytesRead;

         while ((bytesRead = inputStream.read(buffer, 3, 4)) != -1) { // Read 4 bytes at index 3
            System.out.println("Bytes read: " + bytesRead);
            System.out.println("Buffer content: " + new String(buffer, 0, buffer.length)); // Print full buffer
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output(if example.txt contains "Microservices")

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

Bytes read: 4
Buffer content:    Micr
Bytes read: 4
Buffer content:    ices

Explanation

  • Uses BufferedInputStream, which supports efficient reading.

  • Reads 4 bytes at a time, starting from index 3 in buffer.

  • Prints buffer contents after each read operation.

java_io_inputstream.htm
Advertisements