Java Reference
In-Depth Information
GETTING THE CONTENTS OF A DIRECTORY
The
newDirectoryStream()
method in the
Files
class provides you with the means to access the contents
of a directory as a stream of
Path
objects. The method returns a reference of type
java.nio.file.DirectoryStream<Path>
, which is an interface type. You haven't met this form of type
syntax before so just take it as given for the time being. This is a
generictype
, which is a parameterized type
where the type parameter appears between the angled brackets, so this is a
DirectoryStream
type custom-
ized to work with
Path
objects. You learn how to define and use generic types in Chapter 13.
Because the
DirectoryStream<Path>
type implements
Iterable<Path>
, you can use the collection-
based
for
loop to access the
Path
objects in the stream. For example:
Path currentPath = Paths.get(System.getProperty("user.dir"));
a
DirectoryStream<Path> paths = null;
try {
paths = Files.newDirectoryStream(currentPath);
for(Path path : paths) {
System.out.println(path.getFileName());
}
} catch(NotDirectoryException e) {
System.err.println(currentPath + " is not a directory." + e);
} catch(IOException e) {
System.err.println("I/O error." + e);
}
This fragment displays the contents of the current directory. The
newDirectoryStream()
method that
creates the
DirectoryStream<Path>
stream can throw an exception of type
IOException
if an I/O error
occurs, or an exception of type
java.nio.file.NotDirectoryException
if it is called for a
Path
object
that does not reference a directory. Note that this fragment only lists the contents of the current directory
specified by
currentPath
. The contents of any directories in the current directory are not retrieved, only
the directories themselves.
There is another version of the
newDirectoryStream()
method that accepts a second argument of type
String
that specifies a filter for the directory entries that are retrieved. The filter string is a form of regular
EFFECT
Matches zero or more characters of a name without crossing a directory boundary, that is without
passing over a separator character.
*
Matches zero or more characters crossing directory boundaries.
**
Matches a single character in a name.
?
Specifies escape characters that would otherwise be interpreted as special characters in a glob.
\
Specifies a
bracket expression
that encloses a set of characters where a single character can match any
character in the set. The characters
*
,
?
, and
\
match themselves in a bracket expression.
[]
Used to specify a range, so
[a-e]
specifies all the lowercase letters
a
though
e
.
-
Specifies the negation of a range so
[!a-e]
specifies that any character other than
a
through
e
is a
match. The
-
character matches itself when it is the first character in a bracket expression.
!