Recursively list files in Java

后端 未结 27 1623
走了就别回头了
走了就别回头了 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:49

    Java 8 provides a nice stream to process all files in a tree.

    Files.walk(Paths.get(path))
            .filter(Files::isRegularFile)
            .forEach(System.out::println);
    

    This provides a natural way to traverse files. Since it's a stream you can do all nice stream operations on the result such as limit, grouping, mapping, exit early etc.

    UPDATE: I might point out there is also Files.find which takes a BiPredicate that could be more efficient if you need to check file attributes.

    Files.find(Paths.get(path),
               Integer.MAX_VALUE,
               (filePath, fileAttr) -> fileAttr.isRegularFile())
            .forEach(System.out::println);
    

    Note that while the JavaDoc eludes that this method could be more efficient than Files.walk it is effectively identical, the difference in performance can be observed if you are also retrieving file attributes within your filter. In the end, if you need to filter on attributes use Files.find, otherwise use Files.walk, mostly because there are overloads and it's more convenient.

    TESTS: As requested I've provided a performance comparison of many of the answers. Check out the Github project which contains results and a test case.

    0 讨论(0)
  • 2020-11-22 00:50

    I came up with this for printing all the files/file names recursively.

    private static void printAllFiles(String filePath,File folder) {
        if(filePath==null) {
            return;
        }
        File[] files = folder.listFiles();
        for(File element : files) {
            if(element.isDirectory()) {
                printAllFiles(filePath,element);
            } else {
                System.out.println(" FileName "+ element.getName());
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:51

    Apart from the recursive traversal one can use a Visitor based approach as well.

    Below code is uses Visitor based approach for the traversal.It is expected that the input to the program is the root directory to traverse.

    public interface Visitor {
        void visit(DirElement d);
        void visit(FileElement f);
    }
    
    public abstract class Element {
        protected File rootPath;
        abstract void accept(Visitor v);
    
        @Override
        public String toString() {
            return rootPath.getAbsolutePath();
        }
    }
    
    public class FileElement extends Element {
        FileElement(final String path) {
            rootPath = new File(path);
        }
    
        @Override
        void accept(final Visitor v) {
            v.visit(this);
        }
    }
    
    public class DirElement extends Element implements Iterable<Element> {
        private final List<Element> elemList;
        DirElement(final String path) {
            elemList = new ArrayList<Element>();
            rootPath = new File(path);
            for (File f : rootPath.listFiles()) {
                if (f.isDirectory()) {
                    elemList.add(new DirElement(f.getAbsolutePath()));
                } else if (f.isFile()) {
                    elemList.add(new FileElement(f.getAbsolutePath()));
                }
            }
        }
    
        @Override
        void accept(final Visitor v) {
            v.visit(this);
        }
    
        public Iterator<Element> iterator() {
            return elemList.iterator();
        }
    }
    
    public class ElementWalker {
        private final String rootDir;
        ElementWalker(final String dir) {
            rootDir = dir;
        }
    
        private void traverse() {
            Element d = new DirElement(rootDir);
            d.accept(new Walker());
        }
    
        public static void main(final String[] args) {
            ElementWalker t = new ElementWalker("C:\\temp");
            t.traverse();
        }
    
        private class Walker implements Visitor {
            public void visit(final DirElement d) {
                System.out.println(d);
                for(Element e:d) {
                    e.accept(this);
                }
            }
    
            public void visit(final FileElement f) {
                System.out.println(f);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:51
        private void fillFilesRecursively(File file, List<File> resultFiles) {
            if (file.isFile()) {
                resultFiles.add(file);
            } else {
                for (File child : file.listFiles()) {
                    fillFilesRecursively(child, resultFiles);
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-22 00:53

    Java 7 will have has Files.walkFileTree:

    If you provide a starting point and a file visitor, it will invoke various methods on the file visitor as it walks through the file in the file tree. We expect people to use this if they are developing a recursive copy, a recursive move, a recursive delete, or a recursive operation that sets permissions or performs another operation on each of the files.

    There is now an entire Oracle tutorial on this question.

    0 讨论(0)
  • 2020-11-22 00:53
    public static String getExten(String path) {
        int i = path.lastIndexOf('.');
        if (i > 0) {
           return path.substring(i);
        }
        else return "";
    }
    public static List<String> GetAllFiles(String path, List<String>fileList){
        File file = new File(path);
        
        File[] files = file.listFiles();
        for(File folder:files) {
            if(extensions.contains(getExten(folder.getPath()))) {
                fileList.add(folder.getPath());
            }
        }
        File[] direcs = file.listFiles(File::isDirectory);
        for(File dir:direcs) {
            GetAllFiles(dir.getPath(),fileList);
        }
        return fileList;
        
    }
    

    This is a simple recursive function that should give you all the files. extensions is a list of string that contains only those extensions which are accepted. Example extensions = [".txt",".docx"] etc.

    0 讨论(0)
提交回复
热议问题