How do I iterate through the files in a directory

2018-12-31 09:26发布

I need to get a list of all the files in a directory, including files in all the sub-directories. What is the standard way to accomplish directory iteration with Java?

标签: java
8条回答
一个人的天荒地老
2楼-- · 2018-12-31 10:25

Using org.apache.commons.io.FileUtils

File file = new File("F:/Lines");       
Collection<File> files = FileUtils.listFiles(file, null, true);     
for(File file2 : files){
    System.out.println(file2.getName());            
} 

Use false if you do not want files from sub directories.

查看更多
残风、尘缘若梦
3楼-- · 2018-12-31 10:28

As noted, this is a recursion problem. In particular, you may want to look at

listFiles() 

In the java File API here. It returns an array of all the files in a directory. Using this along with

isDirectory()

to see if you need to recurse further is a good start.

查看更多
登录 后发表回答