Java.io.BufferedReader.read() Method



Description

The java.io.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

Example

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

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 test.txt for reading purpose.
         is = new FileInputStream("c:/test.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();
      }
   }
}

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

ABCDEFGHIJKLMNOPQRSTUVWXYZ

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

**ABCDEFGHIJ**************
java_io_bufferedreader.htm
Advertisements