Reading a plain text file in Java
This code opens the file "filename.txt" and reads it line by line. Each line is printed to the console until the end of the file is reached.
To read a plain text file in Java, you can use the following code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("filename.txt"))) {
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}This code opens the file "filename.txt" and reads it line by line. Each line is printed to the console until the end of the file is reached.
Note that relative paths are resolved from the working directory where the Java program is executed, not the directory containing the source file. If the file is located elsewhere, you will need to specify the full path to the file.
For simpler use cases in Java 8+, you can also use Files.readAllLines() or Files.lines() from the java.nio.file package.