Home > Mobile >  How to check all Empty Folders under a Directory in Java
How to check all Empty Folders under a Directory in Java

Time:06-28

I want to find all empty folders under my E: Drive. When I run below Code it shows all empty folders in the E drive. But the main problem is, it also shows a folder named MS OFFICE TUTORIAL SERIES which is not empty,because, under this folder there are three sub folders also.

But the code always shows that the MS OFFICE TUTORIAL SERIES folder is empty in the list of empty files. Please help to find out where I have made mistake.

My Code:

File directory = new File("E:/");
File[] listFiles = directory.listFiles();
System.out.println("List of Empty Directory\n");
for(int i=0; i<listFiles.length; i  ){
    if(listFiles[i].isDirectory()){
        if(listFiles[i] == null ||  listFiles[i].length() == 0){
            System.out.println(listFiles[i].getName());
        }
    }
}

Screenshot for better understanding

enter image description here

CodePudding user response:

You are using the wrong approach to check if the directory is actually empty or not. According to the Java documentation the usage of length() on directories is undefined "[...]The return value is unspecified if this pathname denotes a directory."

So you might want to do something like:

if(listFiles[i].isDirectory()){
   final var subDirEntries = listFiles[i].list();
   if(subDirEntries.length == 0){
      System.out.println("Empty folder: "   listFiles[i].getName());
   }
}
  • Related