Java Reference
In-Depth Information
D:\Beginning Java SE 7\Projects\ListDirectoryContents directory
contains:
classes is a directory.
ListDirectoryContents.jcd
ListDirectoryContents.jcp
ListDirectoryContents.jcu
ListDirectoryContents.jcw
src is a directory.
src_listdirectorycontents.txt
Filter for .txt:
D:\Beginning Java SE 7\Projects\ListDirectoryContents directory
contains:
src_listdirectorycontents.txt
Filter for .j??:
D:\Beginning Java SE 7\Projects\ListDirectoryContents directory
contains:
ListDirectoryContents.jcd
ListDirectoryContents.jcp
ListDirectoryContents.jcu
ListDirectoryContents.jcw
How It Works
The first two statements in
main()
set up the path to the directory to be explored. The path identified
by
"user.dir"
may not be the same when you run the example in which case you may want to modify
these statements so that you end up with a path with some interesting contents.
The contents of a directory are output by the static
filterDirectoryContents()
method with the
path specified by the first argument and the filter string specified by the second argument. You call
this three times — once without a filter and twice subsequently with two different filters. The
Direct-
oryStream<Path>
object is created in the method by the statement between parentheses following the
try
keyword. If the filter argument is
null
, the statement selects the version of
newDirectoryStream()
that has a single parameter.
The contents of the directory stream is output in the
for
loop. The output statement adds additional text
when an entry in the directory is itself a directory, so you can distinguish files and directories in the out-
put. You can see the effects of the filters on the contents of the directory from the output.
MOVING AND COPYING FILES AND
DIRECTORIES
The static
move()
method in the
Files
class enables you to move a file or directory. It also enables you
to rename a file or directory, as you later see. A directory can only be moved if either it is empty, or if the
operation does not require that its contents be moved — that is, essentially renaming the directory.