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.

![Motion Planning and Navigation — Ch.11: Legged Robot Navigation [KR]](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqftgs44jxvhe8fxlcrvt.png)