Java Reference
In-Depth Information
System.out.format("%s [Directory]%n", dir);
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) {
System.out.format("%s [File, Size: %s bytes]%n",
file, attrs.size());
return CONTINUE;
}
}
// Create an obejct of the DirVisitor
FileVisitor<Path> visitor = new DirVisitor<>();
return visitor;
}
}
build [Directory]
build\built-jar.properties [File, Size: 84 bytes]
build\classes [Directory]
twinkle.txt [File, Size: 117 bytes]
twinkle2.txt [File, Size: 128 bytes]
The getFileVisitor() method creates a FileVisitor object by using the SimpleFileVisitor class to
inherit a file visitor class. In the preVisitDirectory() method, it prints the name of the directory and returns
FileVisitResult.CONTINUE to indicate that it wants to continue processing the entries in the directory. In the
visitFile() method, it prints the name and size of the file and continues the processing. The FileVisitor API traverses
a file tree in depth-first order. However, it does not guarantee the order of the visits of the subdirectories of a directory.
To traverse a file tree, you need to call the walkFileTree() method of the Files class. The walkFileTree() method
will automatically call the method of the visitor object as it walks through the file tree.
The FileVisitor API is very useful whenever you want to take some actions on all entries or some selective entries
in a file tree. Operations such as copying a directory tree, deleting a non-empty directory, finding a file, etc. can be
implemented easily using the FileVisitor API. Listing 10-11 demonstrates how to use the FileVisitor API to delete a
directory tree. You need to specify the path to the directory to be deleted before you run the program. Note that you
will not be able to get the contents of the deleted directory back. Therefore, be careful in experimenting with this
program and do not delete any useful directory accidently.
Listing 10-11. Using the FileVisitor API to Delete a Directory Tree
// DeleteDirectoryTest.java
package com.jdojo.nio2;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.TERMINATE;
import java.nio.file.FileVisitor;
 
Search WWH ::




Custom Search