Java Reference
In-Depth Information
CREATED C:\javatest2
CREATED C:\javatest2\subdir
COPIED C:\javatest\subdir\other.txt -> C:\javatest2\subdir\other.txt
COPIED C:\javatest\subdir\text3.txt -> C:\javatest2\subdir\text3.txt
CREATED C:\javatest2\subdircopy2
COPIED C:\javatest\subdircopy2\other.txt -> C:\javatest2\subdircopy2\other.txt
COPIED C:\javatest\subdircopy2\text3.txt -> C:\javatest2\subdircopy2\text3.txt
COPIED C:\javatest\other.txt -> C:\javatest2\other.txt
COPIED C:\javatest\text1.txt -> C:\javatest2\text1.txt
COPIED C:\javatest\text2.txt -> C:\javatest2\text2.txt
How It Works
Here's how it works:
1.
Although the class is relatively large, most of the operations we've included follow the same general
reasoning: loop over subdirectories until you cannot go any further, then perform operations on
the included files.
2.
Two important notes to keep in mind are that the getFiles method first returns a list of direc-
tories, followed by normal files, so that deletion can first clean up the deepest directory before
working its way up. Another interesting aspect is how we use the PathMatcher class to match a
filename to a glob. The following code snippet can come in handy in other scenarios as well:
Path path = ...;
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);
if (matcher.matches(path.getFileName())
// do something
3.
The “glob:" prefix in the getPathMatcher method should be provided by convention to indicate
your pattern is a glob type.
4.
We've added a check to prevent copying and moving a source to the same target. What would hap-
pen if you tried to move a directory under one of its subdirectories? Can you imagine ways to pre-
vent this (or deal with this case)?
5.
If you're interested in knowing how to copy directories using the visitor pattern offered by the
NIO2 API, you can take a look at this example online: http://docs.oracle.com/javase/
tutorial/essential/io/examples/Copy.java .
Other Methods
Finally, there are a number of additional methods in the Files class that can come in handy. First,
metadata methods such as Files.size(Path p) (returns the size of the file in bytes), Files.
getOwner(Path p, LinkOption... options) , and Files.getLastModifiedTime(Path p,
LinkOption... options) can be used to retrieve (and set) metadata. Secondly, functionality exists
to watch a file for changes. Look up NIO's WatchService if you ever need this feature. Lastly, we
briefly touched on the concept of link. The NIO2 API also provides functionality to create and
modify such links in the file system, but we skipped an in-depth discussion and refer interested inter-
mediate readers to other sources, such as the Java API docs.
Search WWH ::




Custom Search