Java Reference
In-Depth Information
You do not need to write logic in all four methods of your file visitor class. For example, if you want to copy
a directory, you would like the code in the preVisitDirectory() method to create a new directory and the
visitFile() method to copy the file. If you want to delete a directory, you need to delete the entries first. In this case,
you will implement the visitFile() method to delete the files and the postVisitDirectory() method to delete the
directory afterwards.
Let's implement a file visitor that will print the names of all files and subdirectories of a directory. It will also print
the size of the files in bytes.
Listing 10-10 contains the complete program. It prints the details of files and subdirectories of the default
directory. You may get a different output when you run this program.
Listing 10-10. A Program to the Print the Names of Subdirectories and Files of a Directory
// WalkFileTreeTest.java
package com.jdojo.nio2;
import java.io.IOException;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import static java.nio.file.FileVisitResult.CONTINUE;
public class WalkFileTreeTest {
public static void main(String[] args) {
// Get the Path obejct for the default directory
Path startDir = Paths.get("");
// Get a file visitor object
FileVisitor<Path> visitor = getFileVisitor();
try {
// Traverse the contents of the startDir
Files.walkFileTree(startDir, visitor);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static FileVisitor<Path> getFileVisitor() {
// Declare a local class DirVisitor that
// inherits fron the SimpleFileVisitor<Path> class
class DirVisitor<Path> extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
 
Search WWH ::




Custom Search