Java Reference
In-Depth Information
3. Write a program that copies all the files in one directory to another with the paths being entered from
the command line. The names of the file copies should have _old appended to them and no files in the
destination folder should be overwritten.
4. Write a program that outputs a count of the total number of files in each directory in a file tree that is
specified by a path entered on the command line and outputs the total number of directories and files in
the tree. List the directories by name with each name followed by the file count in that directory.
• WHAT YOU LEARNED IN THIS CHAPTER
TOPIC
CONCEPT
File and
Directory
Paths
The Path class encapsulates a relative or absolute path to a file, a symbolic link, or a directory. The item
referenced by a Path object may or may not exist.
Accessing
Files and
Directories
The Files class provides methods that you can use to determine whether or not there is a physical file or
directory corresponding to the path that the object encapsulates.
Checking
for a File
or Direct-
ory
Having established that an entry corresponding to a Path object exists, you can determine whether the
entry is a file or directory by examining its attributes.
Accessing
Attributes
The attributes for an entry corresponding to a Path object can be obtained by calling the static
readBasicFileAttributes() method, which is defined in the Files class. Attributes are returned as an
object of type BasicFileAttributes , and the isDirectory() and isRegularFile() methods for the ob-
ject enable you to determine whether the entry is a directory or a file. The size() attribute method returns
the size of a file in bytes.
Creating
Files and
Directories
The static createFile() or createDirectory() methods in the Files class can create a file or directory
for a Path object. The createDirectory() method only creates a single directory.
Creating a
Directory
Hierarchy
The static createDirectories() method in the Files class creates the directory specified by the Path ar-
gument and all necessary parent directories.
Accessing
the Entries
in a Dir-
ectory
The newDirectoryStream() method in the Files class returns a stream that contains all the entries in the
directory corresponding to a given Path object. You can supply a second argument to the newDirect-
oryStream() method that filters the entries so the stream only makes available a selected subset of the
entries.
Exploring
a File Tree
The static walkFileTree() method in the Files class initiates the process of walking a file tree that is
headed by a directory specified by a Path object. You receive information about the entries in the file tree
by implementing the methods specified in the FileVisitor<Path> interface.
Search WWH ::




Custom Search