Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 760
Anshul Avatar asked Oct 17 '12 06:10

Anshul


2 Answers

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

like image 97
Rajesh Avatar answered Oct 25 '22 15:10

Rajesh


    File file=new File("/mnt/sdcard/yourfolder");
        File[] list = file.listFiles();
        int count = 0;
        for (File f: list){
            String name = f.getName();
            if (name.endsWith(".jpg") || name.endsWith(".mp3") || name.endsWith(".some media extention"))
               count++;
            System.out.println("170 " + count);
        }
like image 24
Roadies Avatar answered Oct 25 '22 16:10

Roadies