Android How do I check the number of files in a directory

Anshul picture Anshul · Oct 17, 2012 · Viewed 20.9k times · Source

I am creating a directory in internal memory of device for storing files for application use.I am using:

File dir = context.getDir(userfavorites, Context.MODE_PRIVATE);

The above code will create a new directory if it does not exists or returns me the existing file object if directory has already been created.What I want to check is the number and name of files this directory contains.How do I use this file object to accomplish this task.

NOTE:I don't want to use external memory of device.And I can't avoid creating directory as well because the files in directory has to be separated from other files that are not in directory.

UPDATED CODE:

private static boolean IsFoldercontainsFiles(Context context) {
        // TODO Auto-generated method stub
        File dir = context.getDir(USER_FAV, Context.MODE_PRIVATE);
        if (dir.exists()) {
                    if (dir.listFiles() == null){
                     return false;} //it never execute this line even though its null
                    else{
            File childfile[] = dir.listFiles();
            Log.i("file no is ", Integer.toString(childfile.length));
            if (childfile.length == 0) {
                return false;
            } else {
                return true;
            }
                }
        } else {
            return false;
        }
    }

Thanks in advance

Answer

Rajesh picture Rajesh · Oct 17, 2012

Check the listFiles method of File that will give you the list of children.