java.io.BufferedReader read(char[] cbuf,int off,int len)

Description :

This java tutorial shows how to use the read(char[] cbuf,int off,int len) method of Scanner class of java.io package. This method returns how many characters has been read on the stream or -1 if the reader reaches the end of stream.

Method Syntax :

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

Parameter Input :

DataType Parameter Description
char[] cbuf Character array that serves as a buffer
int offset this method parameter will dictate where to start on the character array buffer
int len the length of how many character should we read from the character stream

Method Returns :

This method simply returns how many characters has been read and put on the buffer or -1 if we reach the end of the input stream.

Compatibility Version :

Requires Java 1.1 and up

Exception :

IOException

– this method returns an IOException if there is an input / output exception encountered

Discussion :

This method reads characters on the input stream and put a portion on the character buffer array.

This method implements the read method of the Reader class. As an additional convenience, it attempts to read as many characters as possible by repeatedly invoking the read method of the underlying stream. The iterated read continues as long as the following conditions has not been met yet:

  • The specified number of characters have been read as specified on the len method argument.
  • We have not reach the end of stream yet, which means the read method has not return the value -1 which serves as a flag for end of stream.
  • The ready method of the underlying stream returns false, indicating that further input requests would block.

Make a not that If the first read on the underlying stream returns -1 to indicate end-of-file then this method returns -1. Otherwise this method returns the number of characters read.

The IndexOutOfBoundsException will be thrown by this method as we are using a character array as buffer, the rules in dealing with array must also apply. Thus make sure that the characters we want to store on our buffer must not exceed the size of the array.

Java Code Example :

This java example source code demonstrates the use of ead(char[] cbuf,int off,int len) method of BufferedReader class. Basically it reads the characters and put a portion of it to the character buffer.

Sample Output :

Running the delimiter() method example source code of Scanner class will give you the following output

Exception Scenario :

Similar Method :

  • N/A

Suggested Reading List :

References :