Java SimpleFileVisitor extend pre Visit Directory

Introduction

Enum Constants of FileVisitResult and Their Descriptions

  • CONTINUE
  • SKIP_SIBLINGS
  • SKIP_SUBTREE
  • TERMINATE
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
  public static void main(String[] args) {
    Path startDir = Paths.get("C:/");
    FileVisitor<Path> visitor = new DirVisitor<>();

    try {/*from   w  w w.  j a v a 2s . co  m*/
      // Traverse the contents of the startDir
      Files.walkFileTree(startDir, visitor);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

class DirVisitor<Path> extends SimpleFileVisitor<Path> {
  @Override
  public FileVisitResult preVisitDirectory(Path dir,
      BasicFileAttributes attrs) {
    System.out.format("%s [Directory]%n", dir);
    return FileVisitResult.CONTINUE;
  }

  @Override
  public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {

    System.out.format("%s [File, Size: %s bytes]%n", file, attrs.size());
    return FileVisitResult.CONTINUE;
  }
}



PreviousNext

Related