Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading all files in the Android file system

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?

like image 324
kholofelo Maloma Avatar asked Aug 11 '11 17:08

kholofelo Maloma


1 Answers

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

like image 142
Shash316 Avatar answered Nov 12 '22 23:11

Shash316