发布于 2011-02-07 08:57:34
如果您有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.
}
发布于 2011-02-07 09:03:14
我想有很多方法可以做你想要的东西。这是我使用的一种方法。使用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"}
发布于 2011-02-07 09:00:38
这里有一个例子,列出了我桌面上的所有文件。您应该将path变量更改为您的路径。
您应该放置自己的代码对文件进行操作,而不是使用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]);
}
}
}
https://stackoverflow.com/questions/4917326
复制相似问题