Recursively list files in Java

后端 未结 27 1624
走了就别回头了
走了就别回头了 2020-11-22 00:29

How do I recursively list all files under a directory in Java? Does the framework provide any utility?

I saw a lot of hacky implementations. But none from the fra

相关标签:
27条回答
  • 2020-11-22 00:54

    In Java 8, we can now use the Files utility to walk a file tree. Very simple.

    Files.walk(root.toPath())
          .filter(path -> !Files.isDirectory(path))
          .forEach(path -> System.out.println(path));
    
    0 讨论(0)
  • 2020-11-22 00:55

    // Ready to run

    import java.io.File;
    
    public class Filewalker {
    
        public void walk( String path ) {
    
            File root = new File( path );
            File[] list = root.listFiles();
    
            if (list == null) return;
    
            for ( File f : list ) {
                if ( f.isDirectory() ) {
                    walk( f.getAbsolutePath() );
                    System.out.println( "Dir:" + f.getAbsoluteFile() );
                }
                else {
                    System.out.println( "File:" + f.getAbsoluteFile() );
                }
            }
        }
    
        public static void main(String[] args) {
            Filewalker fw = new Filewalker();
            fw.walk("c:\\" );
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 00:56

    No external libraries needed.
    Returns a Collection so you can do whatever you want with it after the call.

    public static Collection<File> listFileTree(File dir) {
        Set<File> fileTree = new HashSet<File>();
        if(dir==null||dir.listFiles()==null){
            return fileTree;
        }
        for (File entry : dir.listFiles()) {
            if (entry.isFile()) fileTree.add(entry);
            else fileTree.addAll(listFileTree(entry));
        }
        return fileTree;
    }
    
    0 讨论(0)
  • 2020-11-22 00:56

    Non-recursive BFS with a single list (particular example is searching for *.eml files):

        final FileFilter filter = new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.isDirectory() || file.getName().endsWith(".eml");
            }
        };
    
        // BFS recursive search
        List<File> queue = new LinkedList<File>();
        queue.addAll(Arrays.asList(dir.listFiles(filter)));
    
        for (ListIterator<File> itr = queue.listIterator(); itr.hasNext();) {
            File file = itr.next();
            if (file.isDirectory()) {
                itr.remove();
                for (File f: file.listFiles(filter)) itr.add(f);
            }
        }
    
    0 讨论(0)
  • 2020-11-22 00:57

    With Java 7 you can use the following class:

    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 MyFileIterator extends SimpleFileVisitor<Path>
    {
        public MyFileIterator(String path) throws Exception
        {
            Files.walkFileTree(Paths.get(path), this);
        }
    
        @Override
        public FileVisitResult visitFile(Path file,
                BasicFileAttributes attributes) throws IOException
        {
            System.out.println("File: " + file);
            return FileVisitResult.CONTINUE;
        }
    
        @Override
        public FileVisitResult preVisitDirectory(Path dir,
                BasicFileAttributes attributes) throws IOException
        {
            System.out.println("Dir: " + dir);
            return FileVisitResult.CONTINUE;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:00

    My version (of course I could have used the built in walk in Java 8 ;-) ):

    public static List<File> findFilesIn(File rootDir, Predicate<File> predicate) {
            ArrayList<File> collected = new ArrayList<>();
            walk(rootDir, predicate, collected);
            return collected;
        }
    
        private static void walk(File dir, Predicate<File> filterFunction, List<File> collected) {
            Stream.of(listOnlyWhenDirectory(dir))
                    .forEach(file -> walk(file, filterFunction, addAndReturn(collected, file, filterFunction)));
        }
    
        private static File[] listOnlyWhenDirectory(File dir) {
            return dir.isDirectory() ? dir.listFiles() : new File[]{};
        }
    
        private static List<File> addAndReturn(List<File> files, File toAdd, Predicate<File> filterFunction) {
            if (filterFunction.test(toAdd)) {
                files.add(toAdd);
            }
            return files;
        }
    
    0 讨论(0)
提交回复
热议问题