Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java 8, what is the most preferred and concise way of printing all the lines in a file?

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!

like image 766
The Coordinator Avatar asked Oct 26 '13 09:10

The Coordinator


People also ask

What would be a good way of describing streams in Java 8?

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.

What is the purpose of MAP method of stream in Java 8?

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.


2 Answers

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
 } 
like image 116
The Coordinator Avatar answered Oct 21 '22 10:10

The Coordinator


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);
like image 42
assylias Avatar answered Oct 21 '22 09:10

assylias