Mike
Mike

Reputation: 530

Android: checking directories on sdcard

i need to list only the files present on a sdcard.

With the following code:

File sdcard=new File(Environment.getExternalStorageDirectory().getAbsolutePath());
if(sdcard.isDirectory()){
      String files[]=  sdcard.list();
      for(int i=0;i<files.length;i++){
            File f=new File(files[i]);

            if(!f.isDirectory())
                Log.d("FILES",files[i]);
      } 
}

I see also in the log the subdirectories. What am i doing wrong?

Upvotes: 0

Views: 197

Answers (2)

James Black
James Black

Reputation: 41858

I think the problem is that you need to do this recursively:

File sdcard=Environment.getExternalStorageDirectory();

private void logFiles(File sdcard) {
if(sdcard.isDirectory()){
      File[] files=  sdcard.listFiles();
      for(int i=0;i<files.length;i++){
            if(!f.isDirectory())
                Log.d("FILES",files[i]);
            else
               logFiles(files[i]);
      } 
}
}

I haven't tested this out, but the last else is probably what you were missing and you may find listFiles to be a better choice, here, but, you will need to log the filename, not the File as I left here.

Upvotes: 1

citizen conn
citizen conn

Reputation: 15390

Try this:

if(sdcard.isDirectory()){
    File[] files =  sdcard.listFiles();
    for (File f : files){
        if(!f.isDirectory())
            Log.d("FILES",f.getName());
    } 
}  

The key difference is sdcard.files() vs sdcard.listFiles().

Upvotes: 1

Related Questions