Java BufferedReader read() Method
Example
Read the first two characters of a file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Hello World");
myWriter.close();
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));
System.out.println((char) br.read());
System.out.println((char) br.read());
br.close();
}
}
Definition and Usage
The read() method reads one character and returns it as an int (the number code of the character). Use (char) to turn the number into a character. It returns -1 when there are no more characters (the end of the file).
If you give it a char array, it reads many characters at once and stores them in the array. It then returns the number of characters it read, or -1 at the end of the file.
Tip: Use the readLine() method to read a full line of text.
Syntax
One of the following:
public int read()
public int read(char[] cbuf)
public int read(char[] cbuf, int off, int len)
Parameter Values
| Parameter | Description |
|---|---|
| cbuf | Optional. A char array to store the characters in. |
| off | Optional. The position in the array where the first character is stored. |
| len | Optional. The largest number of characters to read. |
Technical Details
| Returns: | The character as an int (0 to 65535), or the number of characters that were read into the array. -1 if the end of the stream is reached. |
|---|---|
| Throws: | IOException - if the reader is closed, or if another I/O error occurs.IndexOutOfBoundsException - if off or len is outside the array. |
Related Pages
❮ BufferedReader Methods