This uses the new Stream with a lambda in a try enclosure.
I would say it is the most preferred and concise way because:
1) It will automatically close the stream when done and properly throw any exceptions.
2) The output of this is lazy. Each line is read after the last line is processed. This is also is closer to the original Java streams based file handling spec.
3) It prints each line in a manner that most closely resembles the data in the file.
4) This is less memory intensive because it does not create an intermediate List or Array such as the Files.readAllLines(...)
5) This is the most flexible, since the Stream object provided has many other uses and functions for working with the data (transforms, collections, predicates, etc.)
try (Stream<String> stream = Files.lines(Paths.get("sample.txt"),Charset.defaultCharset())) {
stream.forEach(System.out::println);
}
If the path and charset are provided and the Consumer can take any Object then this works too:
try (Stream stream = Files.lines(path,charset)) {
stream.forEach(System.out::println);
}
With error handling:
try (Stream<String> stream = Files.lines(Paths.get("sample.txt"),Charset.defaultCharset())) {
stream.forEach(System.out::println);
} catch (IOException ex) {
// do something with exception
}