Reading text files is a fundamental operation in Java programming, allowing you to access and process textual data stored in files. Whether you need to extract information from log files, parse configuration files, or analyze large text-based datasets, understanding how to read text files is essential for every Java programmer.
This Java program utilizes a Scanner object to read a file named “memo.txt” line by line and prints each line to the console. It also includes a try-catch block that catches the FileNotFoundException and displays an error message if the file is not found.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String filename = "memo.txt";
File file = new File(filename);
try (Scanner reader = new Scanner(file)) {
while(reader.hasNext()) {
String line = reader.nextLine();
System.out.println(line);
}
System.out.printf("Successfully read file '%s'.\n", filename);
} catch (FileNotFoundException e) {
// handle file not found exception
System.out.println(
"File '" + filename + "' not found. " +
"Please check that the file exists in the current directory."
);
}
}
}
I sincerely hope that you find this code helpful. If you wish to learn more about Java, please subscribe to our newsletter today and continue your Java learning journey with us!