Java Reference
In-Depth Information
} catch(IOException e) {
e.printStackTrace();
}
}
}
Directory "FileTreeWalking"
The path for the treeBase object will be the directory containing the samples that came with the JDK 7.
I set the depth to be explored to 3 in an attempt to keep the volume of output down, but there is still quite
a lot of it.
How It Works
Calling the static getProperty() method obtains the Path object for the Java home directory. Calling
fetParent() for this path returns the parent directory. Calling resolve() with the “sample” argument
returns the absolute path to the samples directory that comes with JDK 7.
The main() method uses the version of the walkFileTree() method that accepts four arguments. I chose
to do this because it permits the tree depth to be limited. Note how the set of FileVisitOption options
is created. In general you can supply any number of arguments to the of() method for an EnumSet<>
object to include them in the set. The last argument to the walkFileTree() method is the FileVisitor
object whose methods will be called in the tree-walking process.
I chose a simple task of listing the contents of a tree, but of course you can implement much more com-
plex operations. You could output the size of each file in addition to its path very easily. You could search
for all files of a particular type for example and copy or move them to another directory somewhere. The
file-walking mechanism is a very powerful capability that can accommodate most of what you are likely
to want to do.
SUMMARY
In this chapter, I discussed how you work with file and directory paths, and the facilities for checking and
inspecting physical files and directories. You will use more of the methods defined by the Files class in
the chapters that follow. The topics discussed here and in the previous chapter provide the foundations for
reading and writing files, which you will learn about in the next three chapters.
EXERCISES
You can download the source code for the examples in the topic and the solutions to the following exer-
cises from www.wrox.com .
1. Write a program that lists all the directories in a directory defined by a path specified as a command-
line argument.
2. Write a program to list all the files with a given extension in a directory. The absolute path for the
directory and the extension should be read from the command line. If the extension is absent from the
command-line input, the program should list all the files in the specified directory.
Search WWH ::




Custom Search