如何在Java中扫描文件夹?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/189094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:06:03  来源:igfitidea点击:

How to scan a folder in Java?

javafiledirectory

提问by Lipis

How can I get list all the files within a folder recursively in Java?

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

采纳答案by volley

Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that File.listFiles()returns null for non-directories.

不确定您想如何表示树?无论如何,这是一个使用递归扫描整个子树的示例。文件和目录被同等对待。请注意,File.listFiles()对于非目录返回 null。

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 offers a couple of improvements. For example, DirectoryStreamprovides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.

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);
            }
        }
    }
}

Note that the dreaded null return value has been replaced by IOException.

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

Java 7 also offers a tree walker:

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;
        }
    });
}

回答by OscarRyz

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() );
        }
    }
}

It displays indistinctly files and folders.

它模糊地显示文件和文件夹。

See the methods in File class to order them or avoid directory print etc.

请参阅 File 类中的方法以对它们进行排序或避免目录打印等。

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

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

回答by Brandon DuRette

Check out Apache Commons FileUtils (listFiles, iterateFiles, etc.). Nice convenience methods for doing what you want and also applying filters.

查看 Apache Commons FileUtils(listFiles、iterateFiles 等)。做你想做的事和应用过滤器的好方法。

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

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

回答by Tom Hawtin - tackline

In JDK7, "more NIO features" should have methods to apply the visitor pattern over a file tree or just the immediate contents of a directory - no need to find all the files in a potentially huge directory before iterating over them.

在 JDK7 中,“更多 NIO 功能”应该有方法将访问者模式应用于文件树或目录的直接内容 - 在遍历它们之前无需在潜在的巨大目录中查找所有文件。

回答by Leonel

You can also use the FileFilterinterface to filter out what you want. It is best used when you create an anonymous class that implements it:

您还可以使用该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();
            }});
    }
}

回答by Ohad Dan

Visualizing the tree structure was the most convenient way for me :

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

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;
}

回答by Rohit sharma

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);        
    }
} 

Here diris Directory to be scanned. e.g. c:\

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