如何在Java中遍历特定目录中的文件?

132

2
最佳迭代Java目录的方式是什么? - Olhovsky
1
这是一个重复的问题,但不是关于深度遍历(“包括所有子目录中的文件”)的那个问题。请参见如何在Java中迭代目录中的文件? - Andy Thomas
4个回答

221

如果你有目录名在 myDirectoryPath 中,

import java.io.File;
...
  File dir = new File(myDirectoryPath);
  File[] directoryListing = dir.listFiles();
  if (directoryListing != null) {
    for (File child : directoryListing) {
      // Do something with child
    }
  } else {
    // Handle the case where dir is not really a directory.
    // Checking dir.isDirectory() above would not be sufficient
    // to avoid race conditions with another process that deletes
    // directories.
  }

1
Javado在listFiles()中说:“表示目录本身和目录的父目录的路径名不包括在结果中。” - pihentagy
1
如果您想要当前文件夹,可以使用 new File("."); - SüniÚr

35

我想有很多方法可以实现你想要的功能。这是我使用的一种方法。使用 commons.io 库,您可以迭代目录中的文件。您必须使用 FileUtils.iterateFiles 方法并处理每个文件。

您可以在此处找到相关信息:http://commons.apache.org/proper/commons-io/download_io.cgi

以下是一个示例:

Iterator it = FileUtils.iterateFiles(new File("C:/"), null, false);
        while(it.hasNext()){
            System.out.println(((File) it.next()).getName());
        }

如果你想进行筛选,可以更改 null 并添加一个扩展名列表。 例如:{".xml",".java"}


3
如果没有这个库,而只是使用Java自带的工具类,如果这个库包含了很多文件,你会遇到StackOverflowError错误。(http://java.sun.com/javase/6/docs/api/java/lang/StackOverflowError.html) - Rihards
1
在最新版本(2.6)的commons.io中,您的调用将类似于FileUtils.iterateFiles(new File("C:/"), null, null)(忽略子目录),或者例如FileUtils.iterateFiles(new File("C:/"), new SuffixFileFilter(".java"), null)以对文件扩展名应用过滤器。 - jammartin

11

这是一个列出我的桌面上所有文件的示例。你应该将路径变量更改为你自己的路径。

不要使用System.out.println打印文件名,而应该放置自己的代码来处理该文件。

public static void main(String[] args) {
    File path = new File("c:/documents and settings/Zachary/desktop");

    File [] files = path.listFiles();
    for (int i = 0; i < files.length; i++){
        if (files[i].isFile()){ //this line weeds out other directories/folders
            System.out.println(files[i]);
        }
    }
}

4

listFiles 被重写以接受文件过滤器或文件名过滤器,因此如果您只需要过滤功能,则无需使用 apache-commons。虽然它是一个很好的库。 - Mike Samuel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接