Skip to Content
Java Coding Problems
book

Java Coding Problems

by Anghel Leonard
September 2019
Intermediate to advanced
816 pages
18h 47m
English
Packt Publishing
Content preview from Java Coding Problems

136. Streaming a file's content

Streaming a file's content is a problem that can be solved via JDK 8 using the Files.lines() and BufferedReader.lines() methods.

Stream<String> Files.lines​(Path path, Charset cs) reads all the lines from a file as a Stream. This happens lazily, as the stream is consumed. During the execution of the Terminal stream operation, the file's content should not be modified; otherwise, the result is undefined.

Let's take a look at an example that reads the content of the D:/learning/packt/resources.txt file and displays it on the screen (notice that we run the code in a try-with-resources, and so the file is closed by closing the stream):

private static final String FILE_PATH  = "D:/learning/packt/resources.txt"; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Coding Problems - Second Edition

Java Coding Problems - Second Edition

Anghel Leonard
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781789801415Supplemental Content