简体   繁体   中英

Save file to Specific folder on SD card (External Storage Removable)

I tried to save with path context.getExternalFileDirs() , but it saved files to folder /storage/9016-4EF8/Android/data/package/files on SDcard.

File file = new File(context.getExternalFilesDir(null), myFolder);

I searched Android only support read/write on folder of App like /Android/data/package/files , but I want to save the file to specific folder like /storage/9016-4EF8/MyFolder . How can I achieve this?

If you want to write to the whole micro SD card then use Storage Access Framework.

Use Intent.ACTION_OPEN_DOCUMENT_TREE to let the user of your app choose the card.

On Android 7+ have a look at Storage Volumes.

Here is a link to that explains how to let the user select INTERNAL or EXTERNAL storage. You let the user select the path and maintain that static variable and all data will be written to the SQLite DB using the THE_PATH variable

LINK

You can use Environment.getExternalStorageDirectory() this will give you the public external directory to read and write files.

sample code to create a text file in /storage/9016-4EF8/MyFolder/test.txt

File docsFolder = new File(Environment.getExternalStorageDirectory() + "/MyFolder");
if (!docsFolder.exists()) {
   docsFolder.mkdir();
}
File file = new File(docsFolder.getAbsolutePath(),"test.txt"); 

Edit:

public static String getExternalSdCardPath() {
    String path = null;

    File sdCardFile = null;
    List<String> sdCardPossiblePath = Arrays.asList("external_sd", "ext_sd", "external", "extSdCard");

    for (String sdPath : sdCardPossiblePath) {
            File file = new File("/mnt/", sdPath);

            if (file.isDirectory() && file.canWrite()) {
                    path = file.getAbsolutePath();

                    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
                    File testWritable = new File(path, "test_" + timeStamp);

                    if (testWritable.mkdirs()) {
                            testWritable.delete();
                    }
                    else {
                            path = null;
                    }
            }
    }

    if (path != null) {
            sdCardFile = new File(path);
    }
    else {
            sdCardFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
    }

    return sdCardFile.getAbsolutePath();

}

Resources:

https://gist.github.com/PauloLuan/4bcecc086095bce28e22 https://www.codeproject.com/Questions/716256/find-path-of-external-SD-card

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