Java Reference
In-Depth Information
You can obtain the list of entries in a directory as a stream of
Path
.
You can obtain a stream of
•
Path
that is a result of a file search in a specified directory.
Path
that contains the file tree of a specified directory.
I will show some examples of using streams with file I/O in this section. Please refer to the API documentation
for the
java.nio.file.Files
,
java.io.BufferedReader
, and
java.util.jar.JarFile
classes for more details on the
stream related methods.
The
BufferedReader
and
Files
classes contain a
lines()
method that reads a file lazily and returns the
contents as a stream of strings. Each element in the stream represents one line of text from the file. The file needs to
be closed when you are done with the stream. Calling the
close()
method on the stream will close the underlying
file. Alternatively, you can create the stream in a
try-with-resources
statement so the underlying file is closed
automatically.
The program in Listing 13-4 shows how to read contents of a file using a stream. It also walks the entire file tree
for the current working directory and prints the entries in the directory. The program assumes that you have the
luci1.txt
file, which is supplied with the source code, in the current working directory. If the file does not exist, an
error message with the absolute path of the expected file is printed. You may get a different output when you run
the program.
•
You can obtain a stream of
Listing 13-4.
Performing File I/O Using Streams
// IOStream.java
package com.jdojo.streams;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class IOStream {
public static void main(String[] args) {
// Read the contents of teh file luci1.txt
readFileContents("luci1.txt");
// Print the file tree for the current working directory
listFileTree();
}
public static void readFileContents(String filePath) {
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
System.out.println("The file " +
path.toAbsolutePath() + " does not exist.");
return;
}
try(Stream<String> lines = Files.lines(path)) {
// Read and print all lines
lines.forEach(System.out::println);
}