Iterating Over Files in a Directory - Java File Path IO

Java examples for File Path IO:Directory

Introduction

Create a FileVisitor object and perform a desired implementation within its visitFile method.

Demo Code

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
  public static void main(String args[]) {
    FileVisitor<Path> myFileVisitor = new SimpleFileVisitor<Path>() {
      @Override/*from  w w w  . jav  a 2 s  .com*/
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
          throws IOException {
        System.out.println("Visited File: " + file.toString());
        return FileVisitResult.CONTINUE;
      }
    };

    FileSystem fileSystem = FileSystems.getDefault();
    Path directory = fileSystem.getPath(".");
    try {
      Files.walkFileTree(directory, myFileVisitor);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result


Related Tutorials