How to write a file in external sd card and not in device storage?

折月煮酒 提交于 2019-12-04 04:08:11

问题


I tried this:

  public String getFilename() {
    File file = new File(Environment.getExternalStorageDirectory(), "Test2");
    if (!file.exists()) {
        file.mkdirs();
    }
    String uriSting = (file.getAbsolutePath() + "/" + "IMG_" + System.currentTimeMillis() + ".png");
    return uriSting;
}

I tried changing the second line to:

File file = new File("sdcard/Test2");

But still the directory is being created in device storage and not on external sd card.


回答1:


You do not have arbitrary access to removable storage.

On Android 4.4+, you have two main options:

  1. Use getExternalFilesDirs(), getExternalCacheDirs(), or getExternalMediaDirs() (note the plural), all methods on Context. If they return 2+ locations, the second and subsequent ones are locations on removable storage that your app can read and write, without any permissions.

  2. Use ACTION_OPEN_DOCUMENT and ACTION_CREATE_DOCUMENT, to allow the user to choose where to place some content, where the user can choose removable storage (or Google Drive, or DropBox, or external storage, or anything else). You wind up with a Uri, not a filesystem path; use ContentResolver to work with that Uri to get streams for reading and writing.



来源:https://stackoverflow.com/questions/38247666/how-to-write-a-file-in-external-sd-card-and-not-in-device-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!