suppose my directory structure is as follows:-
MainFolder
1.file1
2.Folder1
2.1 file2
2.2 file3
2.3 file4
3 file5
4.Folder2
4.1 file6
4.2 file7
Inside main folder total files are 7 as i know structure so can write code to calculate total no of files in main folder
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);
}
}
above code works properly and give total no of files as 7
but if i dont know file structure, and folder inside main folder also contain subfolder and that folder contain file, so above code not give correct answers,
for example:-
MainFolder
1.file1
2.Folder1
2.1 subfolder1
2.1.1 SubFolderOfSubFolder
2.1.1.1 file2
2.1.1.2 file3
2.1.1.3 file4
2.2 file5
3 file6
4.Folder2
4.1 file7
4.2 file8
here total no of files is 8,but above code fails
finally i got this solution
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);