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?
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()
.
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.
精彩评论