Reading all files in the Android file system

2019-03-16 16:42发布

问题:

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