Java Online Compiler
Example: Read File with Files.readAllLines in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Read File with Files.readAllLines import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; // 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 Path filePath = Paths.get(fileName); // Step 1: Get a Path object for the file try { // Step 2: Read all lines from the file into a List of Strings List<String> lines = Files.readAllLines(filePath); // Step 3: Iterate through the list and print each line for (String line : lines) { System.out.println(line); } } catch (IOException e) { // Step 4: Handle I/O errors System.err.println("Error reading the file '" + fileName + "': " + e.getMessage()); } } }
Output
Clear
ADVERTISEMENTS