File I/O - Reading a Text File

Access the contents of a text file with ease using Java's BufferedReader for straightforward file input.

File I/O - Reading a Text File
Photo by Carli Jeen / Unsplash

Access the contents of a text file with ease using Java's BufferedReader for straightforward file input.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    public static void main(String[] args) throws IOException {
        String filePath = "sample.txt";
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
}