![]() | |
|
The utility class java.nio.file.Files
was first introduced in Java 7.0 as part of Java NIO. The JDK 8.0
API adds a couple of additional methods which enables us to use functional streams with files.
Files.find(...)
public static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path,BasicFileAttributes> matcher, FileVisitOption... options) throws IOException
The find(...)
returns a Stream
that is lazily populated with Path
by searching for files in a file tree
rooted at a given starting file.
The find(...)
method walks the file tree in exactly the manner specified by the walk(...)
method. For
each file encountered, the given BiPredicate
is invoked with its Path
and
BasicFileAttributes
. The Path
object is obtained as if by resolving the relative path against
start and is only included in the returned Stream
if the BiPredicate
returns
true
. Compare to calling filter on the Stream
returned by walk(...)
method, this
method may be more efficient by avoiding redundant retrieval of the BasicFileAttributes
.
The returned stream encapsulates one or more DirectoryStreams
. If timely disposal of file system resources
is required, the "try-with-resources" construct should be used to ensure that the stream's close()
method is invoked
after the stream operations are completed. Operating on a closed stream will result in an IllegalStateException
.
If an IOException
is thrown when accessing the directory after returned from this method, it is wrapped in an
UncheckedIOException
which will be thrown from the method that caused the access to take place.
The next example demonstrates how to find files in a directory or it's sub-directories:
C:\temp LibPathFinder.java
public static void main(String[] args) throws IOException { Path start = Paths.get("C:\\temp"); int maxDepth = 5; try (Stream<Path> stream = Files.find(start, maxDepth, (path, attr) -> String.valueOf(path).endsWith(".java"))) { String joined = stream .sorted() .map(String::valueOf) .collect(Collectors.joining("; ")); System.out.println("Found: " + joined); } }
The method find(...)
accepts three arguments:
The directory path start
is the initial starting point
The maxDepth
defines the maximum folder depth to be searched
A matching predicate defines the search logic
In the above example we search for all Java files (filename ends with .java
) under C:\temp
directory (limited depth is
5 sub-directories).
Sample output:
Found: C:\temp\LibPathFinder.java
Files.lines(...)
public static Stream<String> lines(Path path) throws IOException
The lines()
method reads all lines from a file as a Stream
. Bytes from the file are decoded
into characters using the UTF-8 charset.
The next example demonstrates how to print a file to console:
public static void main(String[] args) throws IOException { Path f = Paths.get("C:\\temp\\LibPathFinder.java"); try (Stream<String> stream = Files.lines(f)) { stream.forEach(System.out::println); } }
Files.readAllLines(...)
public static List<String> readAllLines(Path path) throws IOException
The readAllLines(...)
method reads all lines from a file into a List
of String
s. Bytes from the file are decoded into characters using the UTF-8 charset.
The next example demonstrates how to print a file to console:
public static void main(String[] args) throws IOException { Path f = Paths.get("C:\\temp\\LibPathFinder.java"); List<String> list = Files.readAllLines(f); list.stream().forEach(System.out::println); }
Files.walk(...)
public static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) throws IOException
The walk(...)
returns a Stream
that is lazily populated with Path
by walking the
file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are
Path
objects that are obtained as if by resolving the relative path against start.
The stream walks the file tree as elements are consumed. The Stream
returned is guaranteed to have at least
one element, the starting file itself. For each file visited, the stream attempts to read its BasicFileAttributes
.
If the file is a directory and can be opened successfully, entries in the directory, and their descendants will follow
the directory in the stream as they are encountered. When all entries have been visited, then the directory is closed.
The file tree walk then continues at the next sibling of the directory.
The maxDepth
parameter is the maximum number of levels of directories to visit. A value of 0
means
that only the starting file is visited, unless denied by the security manager. A value of
MAX_VALUE
may be used to indicate that all levels should be visited.
The next example demonstrates how to list all files and sub-directories in a directory:
C:\temp │ A.class │ A.java │ └───dir1 B.class B.java
public static void main(String[] args) throws IOException { Path start = Paths.get("C:\\temp"); int maxDepth = 5; try (Stream<Path> stream = Files.walk(start, maxDepth)) { stream.forEach(System.out::println); } }
Sample output:
C:\temp C:\temp\A.class C:\temp\A.java C:\temp\dir1 C:\temp\dir1\B.class C:\temp\dir1\B.java
![]() ![]() ![]() |