Recursively list files in Java

后端 未结 27 1650
走了就别回头了
走了就别回头了 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: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 {
        private final List elemList;
        DirElement(final String path) {
            elemList = new ArrayList();
            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 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);
            }
        }
    }
    

提交回复
热议问题