The FileReader class in Java is used to read character-oriented data from a file.
In this chapter, we will learn what the FileReader class is, why it is used, its declaration, constructors, important methods, and how to read data from files using examples.
The FileReader class is a character-based input stream that is used to read data from a file, and it is commonly used for file handling in Java.
It reads data character by character and internally uses byte streams to decode characters. Unlike FileInputStream, FileReader is suitable for reading text data rather than raw binary data.
The following declaration shows how the FileReader class is defined in Java.
The FileReader class provides constructors to open files in read mode.
This constructor opens the specified file using the file name provided as a string. If the file does not exist, it throws FileNotFoundException.
Syntax:
Here is the syntax:
This constructor opens the specified file using a File object. If the file does not exist, it throws FileNotFoundException.
Syntax:
Here is the syntax:
The following code shows how the constructors of the FileReader class are used.
The FileReader class provides methods to read character data from a file.
| Method | Description |
|---|---|
| int read() | It is used to return a character in ASCII form. It returns -1 at the end of file. |
| void close() | It is used to close the FileReader class. |
The following examples demonstrate how to read data from a file using the FileReader class.
The following example demonstrates how to read a text file character by character using the FileReader class.
File Content (testout.txt):
Welcome to TpointTech.
Output:
Welcome to TpointTech.
The following example demonstrates how to read data from a file using a File object with the FileReader class.
Output:
Welcome to TpointTech.
We request you to subscribe our newsletter for upcoming updates.