Java.io.Reader.read() Method
Description
The java.io.Reader.read(char[] cbuf,int off,int len) method reads characters into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
Declaration
Following is the declaration for java.io.Reader.read() method
public abstract int read(char[] cbuf,int off,int len)
Parameters
cbuf -- Destination buffer
off -- Offset at which to start storing characters
len -- Maximum number of characters to read
Return Value
This method returns the number of characters read, or -1 if the end of the stream has been reached
Exception
IOException -- If the stream does not support mark(), or if some other I/O error occurs
Example
The following example shows the usage of java.io.Reader.read() method.
package com.tutorialspoint;
import java.io.*;
public class ReaderDemo {
public static void main(String[] args) {
String s = "Hello world";
// create a StringReader
Reader reader = new StringReader(s);
// create a char array to read chars into
char cbuf[] = new char[5];
try {
// read characters into a portion of an array.
System.out.println("" + reader.read(cbuf, 0, 5));
// print cbuf
System.out.println(cbuf);
// close the stream
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Let us compile and run the above program, this will produce the following result:
5 Hello