Java Online Compiler
Example: Read File with Scanner in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Read File with Scanner import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; // 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 in the same directory // Step 1: Use try-with-resources to ensure the Scanner is closed automatically try (Scanner scanner = new Scanner(new File(fileName))) { // Step 2: Loop while there are more lines to read while (scanner.hasNextLine()) { // Step 3: Read the next line and print it to the console System.out.println(scanner.nextLine()); } } catch (FileNotFoundException e) { // Step 4: Handle the case where the file does not exist System.err.println("Error: The file '" + fileName + "' was not found. " + e.getMessage()); } } }
Output
Clear
ADVERTISEMENTS