Java Reference
In-Depth Information
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
// Delete the file that we are visiting
Files.delete(file);
System.out.format("Deleted file %s%n", file);
return CONTINUE;
}
}
// Create an obejct of the DirVisitor
FileVisitor<Path> visitor = new DeleteDirVisitor();
return visitor;
}
}
By default, the Files.walkFileTree() method does not follow symbolic links. If you want the FileVisitor API to
follow the symbolic links, you need to use another version of the walkFileTree() method that lets you specify the
FileVisitOption.FOLLOW_LINKS as an option. It also lets you specify the maximum depth, which is the maximum
number of levels of a directory to visit. Specifying the depth as 0 visits only the starting file. You can specify
Integer.MAX_VALUE as the depth to visit all levels. The following snippet of code shows how to use the walkFileTree()
method to follow a symbolic link:
import java.util.Set;
import java.util.EnumSet;
import java.nio.file.Path;
import java.nio.file.Files;
import java.io.IOException;
import java.nio.file.FileVisitor;
import java.nio.file.FileVisitOption;
import static java.nio.file.FileVisitOption.FOLLOW_LINKS;
...
Path startDir = get the path to the starting directory;
FileVisitor<Path> visitor = get a file visitor;
// Prepare the set of options
Set<FileVisitOption> options = EnumSet.of(FOLLOW_LINKS);
// Visit all levels
int depth = Integer.MAX_VALUE;
// Walk the file tree with all levels and following the symbolic links
Files.walkFileTree(startDir, options, depth, visitor);
 
Search WWH ::




Custom Search