java 文件 迭代_如何在Java中迭代某個目錄的文件? [重復]

I want to process each file in a certain directory using Java.

我想使用Java處理某個目錄中的每個文件。

What is the easiest (and most common) way of doing this?

這樣做最簡單(也是最常見)的方法是什么?

4 个解决方案

#1

146

If you have the directory name in myDirectoryPath,

如果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.

}

#2

28

I guess there are so many ways to make what you want. Here's a way that I use. With the commons.io library you can iterate over the files in a directory. You must use the FileUtils.iterateFiles method and you can process each file.

我想有很多方法可以制作你想要的東西。這是我使用的一種方式。使用commons.io庫,您可以遍歷目錄中的文件。您必須使用FileUtils.iterateFiles方法,並且可以處理每個文件。

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

Here's an example:

這是一個例子:

Iterator it = FileUtils.iterateFiles(new File("C:/"), null, false);

while(it.hasNext()){

System.out.println(((File) it.next()).getName());

}

You can change null and put a list of extentions if you wanna filter. Example: {".xml",".java"}

如果要過濾,可以更改null並列出擴展列表。示例:{“。xml”,“。java”}

#3

6

Here is an example that lists all the files on my desktop. you should change the path variable to your path.

這是一個列出我桌面上所有文件的示例。您應該將路徑變量更改為您的路徑。

Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.

您應該放置自己的代碼來操作文件,而不是使用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

3

Use java.io.File.listFiles

Or

If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles

使用java.io.File.listFiles或者如果要在迭代之前過濾列表(或任何更復雜的用例),請使用apache-commons FileUtils。 FileUtils.listFiles

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值