![]() |
VOOZH | about |
The FileReader class in Java is used to read data from a file in the form of characters. It is a character-oriented stream that makes it ideal for reading text files. If you want to read binary data (like images or videos), use FileInputStream instead.
The class declaration of FileReader is as follows:
public class FileReader extends InputStreamReader
FileReader is a subclass of InputStreamReader, which in turn extends Reader.
Example: Reading Data from a File Using FileReader
Output:
It inherits from InputStreamReader, which in turn extends Reader and ultimately Object.
The Constructors inside FileReader are shown in the table below.
Creates a new FileReader object to read data from a file with the given name.
FileReader fr = new FileReader("example.txt");
Creates a new FileReader object to read from the specified File object.
File file = new File("example.txt");
FileReader fr = new FileReader(file);
Creates a FileReader using the specified file descriptor. It is often used when working with low-level file handling.
FileDescriptor fd = FileDescriptor.in;
FileReader fr = new FileReader(fd);
The methods under FileReader are shown in the table below.
| Method | Description |
|---|---|
| read() | Reads a single character and returns it, or -1 if the end of the stream is reached. |
| read(char[] charBuffer, int offset, int length) | Reads characters into the given buffer starting at offset up to length characters. Returns the number of characters read or -1 if the stream ends. |
| ready() | Checks if the stream is ready to be read (i.e., input buffer is not empty). |
| getEncoding() | Returns the name of the character encoding used by the stream. |
| close() | Closes the stream and releases system resources. |