In the snippet below you’ll learn to open file for reading using Files.newBufferedReader()
method in JDK 7. This method returns a java.io.BufferedReader
which makes a backward compatibility with the old I/O system in Java.
To read a file you’ll need to provide a Path
and the Charset
to the newBufferedReader()
method arguments.
package org.kodejava.io;
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FilesNewBufferedReader {
public static void main(String[] args) {
Path logFile = Paths.get("app.log");
try (BufferedReader reader =
Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Thanks for this! Really helpful