Reading all files in the Android file system

后端 未结 1 1875
遇见更好的自我
遇见更好的自我 2021-02-06 14:31

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

1条回答
  •  不思量自难忘°
    2021-02-06 15:16

    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

    0 讨论(0)
提交回复
热议问题