Search code examples
androidfor-loopdirectoryis-empty

How to check if folder is empty in loop?


I have one problem I know how to check if folder is empty, but I always get an error when I check if folder is empty in loop, here is example of my code which doesn't work.

String sdcard = Environment.getExternalStorageDirectory().toString();
        File file = new File(sdcard);
        File subFiles[] = file.listFiles();
        for(int i=0; i<subFiles.length; i++) {
            File subFile = new File(sdcard +"/"+ subFiles[i].getName());
            if(subFile.isDirectory() && subFile.listFiles().length==0) {

            }
        }

I always get the error in my condition.


Solution

  • Here's a better version of your code, it's a recursive one also, means it will search for all the empty folders on the storage. Actually, the null check is not a right thing to make here, cause the documentation tells that null will only be returned if file is not a directory.

    public static void traverseEmptyFolders(File root) {
            if (root.isFile()) {
                throw new IllegalArgumentException("Argument should be a directory.");
            }
            for (File file : root.listFiles()) {
                if (file.isDirectory()) {
                    File[] contents = file.listFiles(); 
                    if (contents == null || contents.length == 0) {
                        // do something for an empty folder
                    } else {
                        traverseEmptyFolders(file);
                    }
                }
            }
        }
    
        public static void someOtherMethod() {
            traverseEmptyFolders(Environment.getExternalStorageDirectory());
        }
    

    Let me know if this works.