Java FileReader read() Method
Example
Read a file one character at a time:
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();
FileReader myReader = new FileReader("filename.txt");
int c;
while ((c = myReader.read()) != -1) {
System.out.print((char) c);
}
myReader.close();
}
}
Definition and Usage
The read() method reads one character from the file 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 or a CharBuffer, it reads many characters at once and stores them there. It then returns the number of characters it read, or -1 at the end of the file.
Tip: To read a file line by line, put the FileReader inside a BufferedReader and use its readLine() method.
Syntax
One of the following:
public int read()
public int read(char[] cbuf)
public int read(char[] cbuf, int off, int len)
public int read(CharBuffer target)
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. |
| target | Optional. A CharBuffer (from the java.nio package) to store the characters in. |
Technical Details
| Returns: | The character as an int (0 to 65535), or the number of characters that were read into the array or buffer. -1 if the end of the file 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
❮ FileReader Methods