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(); }
Enter fullscreen mode
Exit fullscreen mode
}
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.…