Java Online Compiler
Example: Read File with BufferedReader in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Read File with BufferedReader import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { String fileName = "sample.txt"; // Ensure this file exists // Step 1: Use try-with-resources for BufferedReader try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String line; // Step 2: Read lines one by one until the end of the file (null) while ((line = reader.readLine()) != null) { // Step 3: Print each line to the console System.out.println(line); } } catch (IOException e) { // Step 4: Handle potential I/O errors (e.g., file not found, read errors) System.err.println("Error reading the file '" + fileName + "': " + e.getMessage()); } } }
Output
Clear
ADVERTISEMENTS