Reading all files in the Android file system

I am writing an Android mediaPlayer application, so I want to scan all the files on the whole phone (i.e. SDK and phone memory). I can read from an SD card, 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 application crashes. How can I access all the files on the SD card, as well as the files on the phone itself?

+4
source share
1 answer

Never use / sdcard / path. It is not guaranteed to work all the time.

Use the code below to get the path to the sdcard directory.

 File root = Environment.getExternalStorageDirectory(); String rootPath= root.getPath(); 

In the rootPath field, you can create the path to any file on the SD card. For example, if there is an image in /DCIM/Camera/a.jpg, then rootPath + "/DCIM/Camera/a.jpg" will be the absolute path.

However, to list all the files in sdcard, you can use the code below

 String listOfFileNames[] = root.list(YOUR_FILTER); 

listOfFileNames will have the names of all the files that are present on the SD card and pass the criteria set by the filter.

Suppose you want to list only mp3 files, then pass the filter class name below to the 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

+9
source

All Articles