File Reading in Java Using FileReader: Step-by-Step Guide with Examples
📘 File Reading in Java (Using FileReader Class)
What is File Reading in Java?
File Reading in Java is the process of reading data from a file stored on the system. Java provides the FileReader class (not “File Reading”) inside the java.io package to read character-based data from files.
📦 FileReader Class
The FileReader class is used to read text data from a file character by character.
📌 Package
java.io
🧱 Constructor of FileReader
FileReader(String filePath) throws FileNotFoundException
- Opens a file located at the given file path.
- Internally creates an input stream to read data from the file.
- Throws FileNotFoundException if the file does not exist.
🛠️ Methods of FileReader
Method. Descriptionint read(). Reads one character at a time and returns its ASCII (Unicode) valuevoid close(). Closes the input stream and releases system resources
🔄 How File Reading Works (Step by Step)
1. Create a FileReader objectWhen the object is created, the operating system opens an input stream for the file.2. Read data using read() methodReads one character at a time.Returns the ASCII value of the character.Returns -1 when the end of the file is reached.3. Use a loop to read the entire fileSince read() reads only one character, it must be used inside a loop.4. Close the file using close()Closing the stream is mandatory to avoid memory leaks.
💡 Example: Reading a File in Java
import java.io.FileReader;import java.io.IOException;public class FileReadingExample {public static void main(String[] args) throws IOException {FileReader fr = new FileReader("example.txt");int ch;while ((ch = fr.read()) != -1) {System.out.print((char) ch);}fr.close();}}
🌍 Real-Life Example
- Think of FileReader like reading a book letter by letter:
- Opening the book → Creating FileReader object
- Reading each letter → read() method
- Finishing the book → read() returns -1
- Closing the book → close() method
⭐ Key Points to Remember
- FileReader reads character-based data
- Reads one character at a time
- Must use a loop to read full content
- Always close the file after reading
- Returns -1 at end of file
Comments
Post a Comment