Java - BufferedReader read(char[] cbuf, int off, int len) method



Description

The Java BufferedReader read(char[] cbuf, int off, int len) method reads len characters into a specified array, started from offset off. This method reads characters by repeatedly invoking the read method of the underlying stream.

The method stops reading if one of the following becomes true.

  • Specified number of characters of the stream have been read.
  • If the end-of-file has been reached.
  • False returned by ready method.

Declaration

Following is the declaration for java.io.BufferedReader.read(char[] cbuf, int off, int len) method.

public int read(char[] cbuf, int off, int len)

Parameters

  • cbuf − Destination buffer.

  • off − Offset to start storing chracters.

  • len − Number of characters to read.

Return Value

The method returns a character as an integer. If the end of the stream has been reached the method returns -1.

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 −

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Example - Using read(char[] cbuf, int off, int len) method

The following example shows the usage of Java BufferedReader read(char[] cbuf, int off, int len) method.

BufferedReaderDemo.java

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BufferedReaderDemo {
   public static void main(String[] args) throws Exception {
      InputStream is = null; 
      InputStreamReader isr = null;
      BufferedReader br = null;

      try {
         // open input stream example.txt for reading purpose.
         is = new FileInputStream("example.txt");
         
         // create new input stream reader
         isr = new InputStreamReader(is);
         
         // create new buffered reader
         br = new BufferedReader(isr);
      
         // creates buffer
         char[] cbuf = new char[is.available()];
         
         // reads characters to buffer, offset 2, len 10
         br.read(cbuf, 2, 10);
         
         // for each character in the buffer
         for (char c:cbuf) {
         
            // if char is empty
            if(c == (char)0) {
               c = '*';
            }
            
            // prints characters
            System.out.print(c);
         }
                  
      } catch(Exception e) {
         e.printStackTrace();
      } finally {
         // releases resources associated with the streams
         if(is!=null)
            is.close();
         if(isr!=null)
            isr.close();
         if(br!=null)
            br.close();
      }
   }
}

Output

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

**ABCDEFGHIJ**************

Example - Reading Chunks of Characters from a String

The following example shows the usage of Java BufferedReader read(char[] cbuf, int off, int len) method.

BufferedReaderDemo.java

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class BufferedReaderDemo {
   public static void main(String[] args) {
      String input = "Hello, World!";
      char[] buffer = new char[5]; // Buffer to hold characters

      // Initialize BufferedReader with a StringReader
      try (BufferedReader reader = new BufferedReader(new StringReader(input))) {
         int numCharsRead;

         // Read characters in chunks
         while ((numCharsRead = reader.read(buffer, 0, buffer.length)) != -1) {
            // Convert the portion of the buffer read to a string
            System.out.print(new String(buffer, 0, numCharsRead));
         }
      } catch (IOException e) {
         System.err.println("An error occurred: " + e.getMessage());
      }
   }
}

Output

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

Hello, World!

Explanation

  • A BufferedReader is created with a StringReader containing "Hello, World!".

  • A buffer (char[]) of size 5 is used to read the string in chunks of up to 5 characters.

  • The read(char[] buf, int off, int len) method fills the buffer with characters, starting at index off (0 in this case) and reading up to len (buffer length).

  • The numCharsRead variable holds the actual number of characters read, which might be less than len at the end of the stream.

  • The portion of the buffer filled is converted to a string and printed.

Example - Reading a Portion of the Input into a Subsection of the Buffer

The following example shows the usage of Java BufferedReader read(char[] cbuf, int off, int len) method.

BufferedReaderDemo.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class BufferedReaderDemo {
   public static void main(String[] args) {
      String input = "BufferedReader Example";
      char[] buffer = new char[10]; // Buffer larger than needed for each chunk

      // Initialize BufferedReader with a StringReader
      try (BufferedReader reader = new BufferedReader(new StringReader(input))) {
         int numCharsRead;

         // Read characters into a subsection of the buffer
         while ((numCharsRead = reader.read(buffer, 2, 5)) != -1) {
            System.out.print("Buffer content: ");
            for (int i = 0; i < buffer.length; i++) {
               System.out.print(buffer[i]);
            } else {
               System.out.print("_"); // Represent unfilled positions with '_'
            }
         }
         System.out.println();
      } catch (IOException e) {
         System.err.println("An error occurred: " + e.getMessage());
      }
   }
}

Output

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

Buffer content: __Buff_____
Buffer content: __Buffe____
Buffer content: __Buffere___
Buffer content: __BufferExa_
Buffer content: __BufferExam

Explanation

  • A BufferedReader is created with a StringReader containing "Hello, World!".

  • A buffer (char[]) of size 5 is used to read the string in chunks of up to 5 characters.

  • The read(char[] buf, int off, int len) method fills the buffer with characters, starting at index off (0 in this case) and reading up to len (buffer length).

  • The numCharsRead variable holds the actual number of characters read, which might be less than len at the end of the stream.

  • The portion of the buffer filled is converted to a string and printed.

Key Points

  • Reads a Portion− Reads up to len characters into the buffer, starting at the offset off.

  • Partial Fills− At the end of the stream, fewer characters may be read than requested.

  • Return Value− Returns the number of characters read or -1 if the stream ends.

  • Efficiency− More efficient than reading single characters in a loop.

These examples illustrate the versatility of the read(char[] buf, int off, int len) method, from reading in chunks to working with specific sections of a buffer.

java_io_bufferedreader.htm
Advertisements