简体   繁体   中英

Android How to get the root directory from a file (path)

How do I get the root directory of any path. If i have file path /storage/emulated/0/Android/media/com.google.android.talk/Ringtones/, what is the best way for me to return the root directory "storage".

Is the file path always in "/" format, is that safe to split the path based on the character "/" or is there a built in function that I can call?

I need to create a method to return the root files of all the audio files on the android phone.

Here are some paths that I have and I want to start with the root directory and then browse each directory with audio files, so is there any build in method that I can call that will return the first directory?

/storage/emulated/0/media/audio/ringtones/abc.mp3
/storage/emulated/0/Music/Various Artists/music.mp3
/storage/emulated/0/new/Artists/test.mp3

Thanks.

What you are suggesting would work. One way would be to use substring with indexOf.

rootPath = string.substring(0, string.indexOf("/")); 

You can access the root folder from ".apk" as follows:

java.io.File dir = new java.io.File("/storage/emulated/0");

and, can create subfolders with:

void CreateDir() throws IOException {
    java.io.File dir = new java.io.File("/storage/emulated/0/MyApplication");
    dir.mkdir();
}

Normally, you must have write permissions to do this:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

But the problem starts with Android 10 (API level 29) and newer. Each path is null .

To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM