← 返回首页
FileVisitor (Java SE 26 & JDK 26)
JavaScript is disabled on your browser.
Contents  
  1. Description
  2. Method Summary
  3. Method Details
    1. preVisitDirectory(T, BasicFileAttributes)
    2. visitFile(T, BasicFileAttributes)
    3. visitFileFailed(T, IOException)
    4. postVisitDirectory(T, IOException)
Hide sidebar  Show sidebar

Interface FileVisitor<T>

Type Parameters: T - the type of file/directory All Known Implementing Classes: SimpleFileVisitor
public interface FileVisitor<T>
A visitor of files. An implementation of this interface is provided to the Files.walkFileTree methods to visit each file in a file tree.

Usage Examples: Suppose we want to delete a file tree. In that case, each directory should be deleted after the entries in the directory are deleted.

Copy Path start = ... Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { // directory iteration failed throw e; } } });

Furthermore, suppose we want to copy a file tree to a target location. In that case, symbolic links should be followed and the target directory should be created before the entries in the directory are copied.

Copy final Path source = ... final Path target = ... Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetdir = target.resolve(source.relativize(dir)); try { Files.copy(dir, targetdir); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(targetdir)) throw e; } return CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, target.resolve(source.relativize(file))); return CONTINUE; } });

Since: 1.7

Scripting on this page tracks web page traffic, but does not change the content in any way.