Java Files file tree walk

Introduction

A simple example that uses walkFileTree() to display a directory tree.

import java.io.IOException;
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.nio.file.attribute.BasicFileAttributes;

// Create a custom version of SimpleFileVisitor that overrides the visitFile() method. 
class MyFileVisitor extends SimpleFileVisitor<Path> {
   public FileVisitResult visitFile(Path path, BasicFileAttributes attribs) throws IOException {
      System.out.println(path);/*from  w  ww.j a v a2s.c om*/
      return FileVisitResult.CONTINUE;
   }
}

public class Main {
   public static void main(String args[]) {
      String dirname = "\\Java_Dev";

      System.out.println("Directory tree starting with " + dirname + ":\n");

      try {
         Files.walkFileTree(Paths.get(dirname), new MyFileVisitor());
      } catch (IOException exc) {
         System.out.println("I/O Error");
      }
   }
}



PreviousNext

Related