Java 如何遍历文件夹中的所有文件(如果文件名未知)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19190584/
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-12 14:55:19  来源:igfitidea点击:

How to loop through all the files in a folder (if the names of the files are unknown)?

javaloops

提问by Buras

There is a folder: C:\\Users\..myfolder

有一个文件夹: C:\\Users\..myfolder

It contains .pdffiles (or any other, say .csv). I cannot change the names of those files, and I do not know the number of those files. I need to loop all of the files one by one. How can I do this?

它包含.pdf文件(或任何其他文件,例如 .csv)。我无法更改这些文件的名称,而且我不知道这些文件的数量。我需要一个一个地循环所有文件。我怎样才能做到这一点?

(I know how to do this if I knew the names)

(如果我知道名字,我就知道该怎么做)

采纳答案by Boris the Spider

Just use File.listFiles

只需使用 File.listFiles

final File file = new File("whatever");
for(final File child : file.listFiles()) {
    //do stuff
}

You can use the FileNameExtensionFilterto filter your files too

您也可以使用FileNameExtensionFilter来过滤文件

final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "pdf", "csv"//, whatever other extensions you want);
final File file = new File("whatever");
for (final File child : file.listFiles()) {
    if(extensionFilter.accept(child)) {
        //do stuff
    }
}

Annoyingly FileNameExtensionFiltercomes from the javax.swingpackage so cannot be used directly in the listFiles()api, it is still more convenient than implementing a file extension filter yourself.

烦人的FileNameExtensionFilter是来自javax.swing包所以不能直接在listFiles()api中使用,还是比自己实现文件扩展名过滤器方便多了。

回答by user2827100

File.listFiles()gives you an array of files in a folder. You can then split the filenames to get the extension and check if it is .pdf.

File.listFiles()为您提供文件夹中的文件数组。然后,您可以拆分文件名以获取扩展名并检查它是否为 .pdf.

File[] files = new File("C:\Users\..myfolder").listFiles();
for (File file : files) {
    if (!file.isFile()) continue;

    String[] bits = file.getName().split(".");
    if (bits.length > 0 && bits[bits.length - 1].equalsIgnoreCase("pdf")) {
        // Do stuff with the file
    }
}

回答by Ali Hashemi

You can use Java.io.File.listFiles()method to get a list of all files and folders inside a folder.

您可以使用Java.io.File.listFiles()方法来获取文件夹内所有文件和文件夹的列表。

回答by Sotirios Delimanolis

So you can have more options, try the Java 7 NIOway of doing this

所以你可以有更多的选择,试试Java 7 NIO 的方式

public static void main(String[] args) throws Exception {
    try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/"))) {
        for (Path path : files) {
            System.out.println(path.toString());
        }
    }
}

You can also provide a filter for the paths in the form of a DirectoryStream.Filterimplementation

您还可以以DirectoryStream.Filter实现的形式为路径提供过滤器

public static void main(String[] args) throws Exception {
    try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/"),
        new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path entry) throws IOException {
                return true; // or whatever you want
            }
        })
    ) {

        for (Path path : files) {
            System.out.println(path.toString());
        }
    }
}

Obviously you can extract the anonymous class to an actual class declaration.

显然,您可以将匿名类提取到实际的类声明中。

Note that this solution cannot return nulllike the listFiles()solution.

请注意,此解决方案不能nulllistFiles()解决方案一样返回。

For a recursive solution, check out the FileVisitorinterface. For path matching, use the PathMatcherinterface along with FileSystemsand FileSystem. There are examples floating around Stackoverflow.

对于递归解决方案,请查看FileVisitor接口。对于路径匹配,将PathMatcher接口与FileSystems和一起使用FileSystem。Stackoverflow 中有很多例子。