Set maximum number of directory levels to visit to ensure that all levels are traversed - Java File Path IO

Java examples for File Path IO:Directory

Description

Set maximum number of directory levels to visit to ensure that all levels are traversed

Demo Code

import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.util.EnumSet;

public class Main {
  public static void main(String[] args) throws Exception {
    Path listDir = Paths.get("C:/folder1"); // define the starting file
    ListTree walk = new ListTree(); // instantiate the walk
    EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); // follow links

    try {/*  w ww. ja  v a2s . c  o  m*/
      Files.walkFileTree(listDir, opts, Integer.MAX_VALUE, walk); // start the
                                                                  // walk
    } catch (IOException e) {
      System.err.println(e);
    }

  }
}

class ListTree extends SimpleFileVisitor<Path> {

  @Override
  public FileVisitResult postVisitDirectory(Path dir, IOException exc) {

    System.out.println("Visited directory: " + dir.toString());

    return FileVisitResult.CONTINUE;
  }

  @Override
  public FileVisitResult visitFileFailed(Path file, IOException exc) {
    System.out.println(exc);

    return FileVisitResult.CONTINUE;
  }
}

Result


Related Tutorials