Java by Petr Sladek
Welcome to the Java 8 files tutorial!
First let’s define our testing variable for this tutorial:
Let’s say we want to read a whole file line after line and print each line to the output console.
In Java 7, we would have to iterate like this:
try (final BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
This boiler plate code is very cumbersome. Let’s see what Java 8 has to offer.
In Java 8, we can simply write this:
Files.readAllLines(Paths.get(fileName)).forEach(System.out::println);
That’s all folks! ;)
This tutorial is available for download!
If you want to run and test all of this in a Java code: