FileReader and BufferedReader in Java
Java provides different classes to read data from files. Two commonly used classes are FileReader and BufferedReader.
Let's understand them with simple examples.
- FileReader
FileReader is used to read characters from a text file.
Example:
Assume we have a file called sample.txt:
Hello Java
Welcome to File Handling
Java Code:
import java.io.FileReader;
public class Main {
public static void main(String[] args) throws Exception {
FileReader reader = new FileReader("sample.txt");
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
}
}
Explanation:
FileReader opens the file.
read() reads one character at a time.
-1 indicates the end of the file.
close() closes the file.
- BufferedReader
BufferedReader is used to read text efficiently. It also provides a method called readLine() to read a complete line.
Java Code:
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) throws Exception {
FileReader file = new FileReader("sample.txt");
BufferedReader reader = new BufferedReader(file);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
Explanation:
FileReader opens the file.
BufferedReader reads the file using a buffer.
readLine() reads one complete line.
null indicates the end of the file.
close() closes the reader.
Top comments (0)