Java Reference
In-Depth Information
for (Path entry: stream) {
System.out.println(entry.getFileName());
}
} catch (IOException | DirectoryIteratorException x) {
System.err.println("An error occurred");
}
}
}
Example output:
$Recycle.Bin
BOOTNXT
Documents and Settings
eclipse
hiberfil.sys
MSOCache
pagefile.sys
PerfLogs
Program Files
Program Files (x86)
ProgramData
swapfile.sys
System Volume Information
temp
Users
Windows
Note that this approach returns all the contents of a directory: files, subdirectories, hidden files,
and links. If you only need a subset, you can just add checks to the for loop using methods
you've seen before. Another way to filter a directory listing is by using a concept called glob-
bing , using the Files.newDirectoryStream(Path folder, String glob) method. A glob
is a special kind of syntax to specify pattern-matching behavior. An asterisk ( * ), for instance,
matches any number of characters; a question mark ( ? ) matches exactly one character. Braces
( {one,two} ) specify a collection of subpatterns, whereas square patterns ( [qwerty] ) convey a set
or range ( [0-9] ) of characters. The following method call, for example, only returns DOC, PDF,
and TXT files:
Files.newDirectoryStream(dir, "*.{txt,doc,pdf}"));
If you only want to retrieve directories, you'll need to write your own filter. To do so, you can
create a class implementing the DirectoryStream.Filter<T> interface (and implementing
the accept method) and use this to invoke the Files.newDirectoryStream(Path folder,
DirectoryStream.Filter filter) method. Just using an if (Files.isDirectory(entry))
continue; line might be easier in this case, however.
Recursing Folders
The last operation we'll take a closer look at involves recursing over the folder tree. When discussing
how to copy, move, or delete paths, we've stated that copying folders just creates an empty folder,
Search WWH ::




Custom Search