Bugs Buggy
Bugs Buggy

Reputation: 1546

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

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.

Upvotes: 3

Views: 1458

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006614

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.

Upvotes: 3

Related Questions