I am writing an Android mediaPlayer app, so I want to scan through all files on the entire phone (i.e. sdcard and phone memory). I can read from the sdcard, but not the root of it. That is, I can just read from the path /sdcard/[folder]/
and it works fine, but if I go to /sdcard/
the app crashes. How can I access all the files on the sdcard, as well as the files on the phone itself?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Never use the /sdcard/ path. it is not guaranteed to work all the time.
Use below code to get the path to sdcard directory.
File root = Environment.getExternalStorageDirectory();
String rootPath= root.getPath();
From rootPath location, you can build the path to any file on the SD Card. For example if there is an image at /DCIM/Camera/a.jpg, then absolute path would be rootPath + "/DCIM/Camera/a.jpg".
However to list all files in the SDCard, you can use the below code
String listOfFileNames[] = root.list(YOUR_FILTER);
listOfFileNames will have names of all the files that are present in the SD Card and pass the criteria set by filter.
Suppose you want to list mp3 files only, then pass the below filter class name to list() function.
FilenameFilter mp3Filter = new FilenameFilter() {
File f;
public boolean accept(File dir, String name) {
if(name.endsWith(".mp3")){
return true;
}
f = new File(dir.getAbsolutePath()+"/"+name);
return f.isDirectory();
}
};
Shash