如何获得主目录和子目录中存在的文件总数,为java中的每种类型的结构工作



假设我的目录结构如下:-
MainFolder
1.file1
2.Folder1
2.1 file2
2.2 file3
2.3 file4
3 file5
4.Folder2
4.1 file6
4.2 file7

据我所知,主文件夹内的文件总数为7,因此可以编写代码来计算主文件夹中的文件总数

public class FileIo {
public static void main(String[] args) throws IOException {
int count1=0;
File f=new File("C:\Users\omshanti\Desktop","mainfolder");
String[] s=f.list();
for(String s1:s){
File f1=new File(f,s1);
if(f1.isFile()){
count1++;
}
if(f1.isDirectory()){
int subdirfilelength=f1.list().length;
count1=count1+subdirfilelength;
}
}
System.out.println("total no of files in h1 folder "+count1);        

}
}

上面的代码工作正常,文件总数为7
,但如果我不知道文件结构,主文件夹中的文件夹也包含子文件夹,该文件夹包含文件,所以上面的代码没有给出正确的答案,
例如:-
MainFolder
1.file1
2.Folder1
2.1子文件夹1
2.1.1 SubFolderOfSubFolder
2.1.1.1文件2
2.1.1.2文件3
2.1.13文件42.2文件5
3文件6
4.文件夹2
4.1文件7
4.2文件8
此处的文件总数为8,但以上代码失败

最终我得到了这个解决方案

int count1=0;
File f=new File("C:\Users\omshanti\Desktop","h1");
String[] s=f.list();
for(int i=0;i<s.length;i++){
File f1=new File(f,s[i]);
if(f1.isFile()){
count1++;
}
else if(f1.isDirectory()){
String[] subdir1=f1.list();
for(int j=0;j<subdir1.length;j++){
File f2 = new File(f1, subdir1[j]);
if (f2.isFile()) {
count1++;

}
else if(f2.isDirectory()){
String[] subdir2=f2.list();
for(int k=0;k<subdir2.length;k++){
File f3 = new File(f2, subdir2[k]);
if (f3.isFile()) {
count1++;

}
else if(f3.isDirectory())
{
String[] subdir3=f3.list();
for (String subdir31 : subdir3) {
File f4 = new File(f3, subdir31);
if (f4.isFile()) {
count1++;

}
}


}
}
}}}
}
System.out.println("total no of files in h1 folder "+count1);        

您可以使用apache commons io的FileUtils.listFiles实现以下功能:

List<File> files = (List<File>) FileUtils.listFiles(new File("/your/path"), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
int nbFiles = files.size();

他们的javadoc说:

查找给定目录中的文件子目录)。

第一个参数是您的路径。第二个将标志设置为"查找文件"。第三个将标志设置为"考虑目录",从而遍历子目录。

在maven中需要以下依赖项:

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

或者在此处下载jar并将其添加到类路径中:commons io:commons io:2.4(或直接链接下载)

Apache站点上的FileUtils javadoc

最新更新