get All Files Under Directory using nio - Java java.nio.file

Java examples for java.nio.file:Files

Description

get All Files Under Directory using nio

Demo Code


import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

public class Main{
    public static List<File> getAllFilesUnderDirectory(File directory,
            final Filter<File> fileFilter) throws IOException {
        final List<File> files = new LinkedList<File>();

        Files.walkFileTree(directory.toPath(),
                new SimpleFileVisitor<Path>() {
                    @Override//  www  .j a va2 s.  com
                    public FileVisitResult preVisitDirectory(Path dir,
                            BasicFileAttributes attrs) throws IOException {
                        if (fileFilter.isPassingFilter(dir.toFile()))
                            files.add(dir.toFile());

                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFile(Path file,
                            BasicFileAttributes attrs) throws IOException {
                        if (fileFilter.isPassingFilter(file.toFile()))
                            files.add(file.toFile());

                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFileFailed(Path file,
                            IOException exc) throws IOException {
                        return FileVisitResult.CONTINUE;
                    }
                });

        return files;
    }
}

Related Tutorials