What is the most preferred and concise way to print all the lines in a file using the new Java 8?
The output must be a copy of the file, line for line as in:
[Line 1 ...]
[Line 2 ...]
The question pertains to Java-8 with lambdas even though there are ways of doing it in older versions. Show what Java-8 is all about!
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another.
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
}
You don't really need Java 8:
System.out.println(Files.readAllLines(path, charset));
If you really want to use a stream or need a cleaner presentation:
Files.readAllLines(path, charset).forEach(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With