Pacific-Design.com

    
Home Index

1. Java

2. Directories

+ Legacy Code

Java / Directories /

Java 7 - SimpleFileVisitor (FileTree)

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;

public class FileTree extends SimpleFileVisitor<Path> {

    /*--------------------------------------------------------------------------------------------*/
    public static void main(String[] args) throws IOException {

        Path fileDir = Paths.get("src/Java_Programming/Files/");
        FileTree visitor = new FileTree();
        Files.walkFileTree(fileDir, visitor);
    }
    /*--------------------------------------------------------------------------------------------*/

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        System.out.println("Leaving dir:\t" + dir);
        return FileVisitResult.CONTINUE;
    }
    /*--------------------------------------------------------------------------------------------*/

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        System.out.println("Going to dir:\t" + dir);
        return FileVisitResult.CONTINUE;
    }
    /*--------------------------------------------------------------------------------------------*/

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        if (attrs.isRegularFile()) {
            System.out.print("Found a file:\t");
        }
        System.out.println(file);
        return FileVisitResult.CONTINUE;
    }
    /*--------------------------------------------------------------------------------------------*/

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        System.err.println("Error: " + exc.getMessage());
        return FileVisitResult.CONTINUE;
    }
    /*--------------------------------------------------------------------------------------------*/
}