代码之家  ›  专栏  ›  技术社区  ›  Lipis

如何扫描Java中的文件夹?

  •  58
  • Lipis  · 技术社区  · 17 年前

    如何在Java中递归地列出文件夹内的所有文件?

    7 回复  |  直到 8 年前
        1
  •  71
  •   volley    13 年前

    不确定要如何表示树?无论如何,这里有一个使用递归扫描整个子树的例子。文件和目录的处理方式相同。注意 File.listFiles() 对于非目录,返回空值。

    public static void main(String[] args) {
        Collection<File> all = new ArrayList<File>();
        addTree(new File("."), all);
        System.out.println(all);
    }
    
    static void addTree(File file, Collection<File> all) {
        File[] children = file.listFiles();
        if (children != null) {
            for (File child : children) {
                all.add(child);
                addTree(child, all);
            }
        }
    }
    

    Java 7提供了一些改进。例如, DirectoryStream 一次提供一个结果-调用方不再需要等待所有I/O操作完成后再执行操作。这允许增量GUI更新、提前取消等。

    static void addTree(Path directory, Collection<Path> all)
            throws IOException {
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
            for (Path child : ds) {
                all.add(child);
                if (Files.isDirectory(child)) {
                    addTree(child, all);
                }
            }
        }
    }
    

    请注意,可怕的空返回值已被IOException替换。

    Java 7还提供了一个 tree walker :

    static void addTree(Path directory, final Collection<Path> all)
            throws IOException {
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
                all.add(file);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    
        2
  •  21
  •   OscarRyz    17 年前
    import java.io.File;
    public class Test {
        public static void main( String [] args ) {
            File actual = new File(".");
            for( File f : actual.listFiles()){
                System.out.println( f.getName() );
            }
        }
    }
    

    它显示不清晰的文件和文件夹。

    请参阅文件类中的方法以对其进行排序或避免目录打印等。

    http://java.sun.com/javase/6/docs/api/java/io/File.html

        3
  •  18
  •   Stefan Ernst    17 年前

    查看apache commons fileutils(listfiles、iteratefiles等)。很好的方便方法来做你想做的事情,也应用过滤器。

    http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html

        4
  •  6
  •   Leonel    17 年前

    您也可以使用 FileFilter 用于筛选出所需内容的接口。当您创建实现它的匿名类时,最好使用它:

    import java.io.File;
    import java.io.FileFilter;
    
    public class ListFiles {
        public File[] findDirectories(File root) { 
            return root.listFiles(new FileFilter() {
                public boolean accept(File f) {
                    return f.isDirectory();
                }});
        }
    
        public File[] findFiles(File root) {
            return root.listFiles(new FileFilter() {
                public boolean accept(File f) {
                    return f.isFile();
                }});
        }
    }
    
        5
  •  2
  •   Ahmed Ashour chim    8 年前
    public static void directory(File dir) {
        File[] files = dir.listFiles();
        for (File file : files) {
            System.out.println(file.getAbsolutePath());
            if (file.listFiles() != null)
                directory(file);        
        }
    } 
    

    在这里 dir 是要扫描的目录。例如 c:\

        6
  •  1
  •   Ohad Dan    14 年前

    可视化树结构是我最方便的方法:

    public static void main(String[] args) throws IOException {
        printTree(0, new File("START/FROM/DIR"));
    }
    
    static void printTree(int depth, File file) throws IOException { 
        StringBuilder indent = new StringBuilder();
        String name = file.getName();
    
        for (int i = 0; i < depth; i++) {
            indent.append(".");
        }
    
        //Pretty print for directories
        if (file.isDirectory()) { 
            System.out.println(indent.toString() + "|");
            if(isPrintName(name)){
                System.out.println(indent.toString() + "*" + file.getName() + "*");
            }
        }
        //Print file name
        else if(isPrintName(name)) {
            System.out.println(indent.toString() + file.getName()); 
        }
        //Recurse children
        if (file.isDirectory()) { 
            File[] files = file.listFiles(); 
            for (int i = 0; i < files.length; i++){
                printTree(depth + 4, files[i]);
            } 
        }
    }
    
    //Exclude some file names
    static boolean isPrintName(String name){
        if (name.charAt(0) == '.') {
            return false;
        }
        if (name.contains("svn")) {
            return false;
        }
        //.
        //. Some more exclusions
        //.
        return true;
    }
    
        7
  •  0
  •   Tom Hawtin - tackline    17 年前

    在JDK7中,“更多NIO特性”应该有方法在文件树或目录的直接内容上应用访问者模式——在迭代之前,不需要在一个可能巨大的目录中查找所有文件。

    推荐文章