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";
...
try (Stream<String> filesStream = Files.lines(
Paths.get(FILE_PATH), StandardCharsets.UTF_8)) {

filesStream.forEach(System.out::println);
} catch (IOException e) {
// handle IOException if needed, otherwise remove the catch block
}

A similar method without arguments is available in the BufferedReader class:

try (BufferedReader brStream = Files.newBufferedReader(
Paths.get(FILE_PATH), StandardCharsets.UTF_8)) {

brStream.lines().forEach(System.out::println);
} catch (IOException e) {
// handle IOException if needed, otherwise remove the catch block
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.187.62