Adam
Adam

Reputation: 2202

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.

Upvotes: 1

Views: 2164

Answers (2)

Hardik4560
Hardik4560

Reputation: 3220

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());

File temp[] = subFiles.length;

        if(subFile.isDirectory() && (temp != null && temp.length == 0)) {

        }
    }

Upvotes: 0

Egor
Egor

Reputation: 40218

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.

Upvotes: 5

Related Questions