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



Description

The Java BufferedInputStream read(byte[] b, int off, int len) method reads len bytes from byte-input stream into a byte array, starting at a given offset. This method repeatedly invokes the read() method of the underlying stream.

The iterated read continues until one of the follwing conditions becomes true −

  • len bytes read.

  • Returns -1, indicating end-of-file.

  • If the available() method of BufferedInputStream returns 0

Declaration

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

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

Parameters

  • b − byte array to be populated.

  • off − starts storing from the offset.

  • len − number of bytes to read.

Return Value

This method does not return any value.

Exception

IOException − If an I/O error occurs.

Assumption

Assuming we have a text file example.txt, which has the following content. This file will be used as an input for our example programs −

ABCDE

Example - Using read() method

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

BufferedInputStreamDemo.java

package com.tutorialspoint;

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

public class BufferedInputStreamDemo {
   public static void main(String[] args) throws Exception {
      InputStream inStream = null;
      BufferedInputStream bis = null;

      try {
         // open input stream test.txt for reading purpose.
         inStream = new FileInputStream("example.txt");
         
         // input stream is converted to buffered input stream
         bis = new BufferedInputStream(inStream);
         
         // read number of bytes available
         int numByte = bis.available();
         
         // byte array declared
         byte[] buf = new byte[numByte];
         
         // read byte into buf , starts at offset 2, 3 bytes to read
         bis.read(buf, 2, 3);
         
         // for each byte in buf
         for (byte b : buf) {
            System.out.println((char)b+": " + b);
         }
      } catch(Exception e) {
         e.printStackTrace();
      } finally {
         // releases any system resources associated with the stream
         if(inStream!=null)
            inStream.close();
         if(bis!=null)
            bis.close();
      }	
   }
}

Output

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

  : 0
  : 0
A: 65
B: 66
C: 67

Example: Using read(byte[] b, int off, int len) to Read into a Buffer

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

BufferedInputStreamDemo.java

package com.tutorialspoint;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;

public class BufferedInputStreamDemo {
    public static void main(String[] args) {
        byte[] data = "BufferedInputStream read example".getBytes();
        // open input stream on bytes for reading purpose.
        try (BufferedInputStream bis = new BufferedInputStream(
		   new ByteArrayInputStream(data))) {
            byte[] buffer = new byte[10]; // Buffer to hold chunks of data
            int bytesRead;

            System.out.println("Reading data into a buffer:");
            while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) {
                // Convert bytes to string and print
                System.out.print(new String(buffer, 0, bytesRead));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output

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

Reading data into a buffer:
BufferedInputStream read example

Explanation

  • Stream Source− A BufferedInputStream wraps a ByteArrayInputStream with byte array data.

  • Buffer Usage

    • A byte array (buffer) of size 10 is created to read chunks of data.

    • The read(byte[] b, int off, int len) method reads up to 10 bytes at a time into the buffer starting at offset 0.

  • Behavior

    • The read() method returns the number of bytes read or -1 if the end of the stream is reached.

    • The bytes are converted to a string and printed to the console.

  • Output− The data is printed in chunks of up to 10 bytes.

Summary

  • Use int read() for reading one byte at a time, which is simple but less efficient for large data.

  • Use int read(byte[] b, int off, int len) for reading chunks of data into a buffer, which is faster and more efficient for processing larger data streams.

java_io_bufferedinputstream.htm