如何在Java中迭代某个目录的文件? [英] How to iterate over the files of a certain directory, in Java?
本文介绍了如何在Java中迭代某个目录的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
在java中遍历目录的最佳方法
我想使用Java处理某个目录中的每个文件。
这样做最简单(最常见)是什么?
解决方案>
如果您在 myDirectoryPath
中有目录名称,
import java.io.File;
...
文件dir = new File(myDirectoryPath);
文件[] directoryListing = dir.listFiles();
if(directoryListing!= null){
for(File child:directoryListing){
// do something with child
}
} else {
//处理dir不是一个目录的情况。
//检查上面的dir.isDirectory()将不足以
//以避免与其他进程删除
//目录的竞争条件。
}
Possible Duplicate:
Best way to iterate through a directory in java?
I want to process each file in a certain directory using Java.
What is the easiest (and most common) way of doing this?
解决方案
If you have the directory name in 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.
}
这篇关于如何在Java中迭代某个目录的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文