Java Reference
In-Depth Information
CHARACTER
SEQUENCE
EFFECT
Specifies a set of subpatterns that can be matched where the subpatterns are separated by commas. For
example,
{exe, txt}
matches either
exe
or
txt
.
{}
All other characters not in
Table 9-5
match themselves. Thus to see only
.exe
files from a directory
stream, you use the glob
"*.exe"
. To see only
.exe
and
.txt
files, you could use
"*.{exe,txt}"
. The
glob
"*.???"
matches any file with a three-character extension.
CLOSING A STREAM
In the code fragment in the previous section, there is no provision for calling the
close()
method for the
DirectoryStream<Path>
object and there really should be. In general, you should not call the
close()
method for a stream in a
try
block that has other stream operations that also throw exceptions because if
such exceptions are thrown, the
close()
method call may be circumvented. Because the
close()
method
itself can throw an exception of type
IOException
that must be caught there is the potential for rather messy
code to take care of all eventualities. A new version of the
try
block was introduced in Java 7 called a
try
block-with-resources
that makes it very easy to ensure that a stream is closed when you are done with it.
The
try
block with resources language facility provides the capability for automatically closing streams
at the end of executing the code in the
try
block, regardless of how execution of the block terminates. This
works with object of any class type that implements the
AutoCloseable
interface.
To call the
close()
method automatically, you must create the stream objects between parentheses that
immediately following the
try
keyword. If you need to create multiple stream objects, just separate the
statements between the parentheses with semicolons. Stream objects that you create here are implicitly
fi-
nal
so they cannot be changed within the
try
block. Here's a revised version of the fragment from the pre-
vious section using a
try
block with resources:
Path currentPath = Paths.get(System.getProperty("user.dir"));
try (DirectoryStream<Path> 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);
}
The
close()
method for
paths
is called after the
try
block code completes, whether or not an exception
is thrown from within the block. The
close()
method is not called if
paths
is
null
.
Let's try this out in an example.
TRY IT OUT: Listing the Contents of a Directory
In this example, we list the entire contents of a directory and then use a filter to select particular entries.