如何在外部 SD 卡而不是设备存储中写入文件? [英] How to write a file in external sd card and not in device storage?

查看:46
本文介绍了如何在外部 SD 卡而不是设备存储中写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过了:

  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");

但目录仍然是在设备存储中创建的,而不是在外部 SD 卡上.

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

推荐答案

您不能随意访问 可移动存储.

在 Android 4.4+ 上,您有两个主要选择:

On Android 4.4+, you have two main options:

  1. 使用 getExternalFilesDirs()getExternalCacheDirs()getExternalMediaDirs()(注意复数),所有方法都在 <代码>上下文.如果它们返回 2+ 个位置,则第二个和后续位置是可移动存储上的位置,您的应用无需任何权限即可读取和写入.

  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.

使用ACTION_OPEN_DOCUMENTACTION_CREATE_DOCUMENT,允许用户选择放置某些内容的位置,用户可以选择移动存储(或 Google Drive,或 DropBox,或 外部存储,或其他任何内容).您最终会得到一个 Uri,而不是文件系统路径;使用 ContentResolver 来处理它Uri 获取读写流.

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.

这篇关于如何在外部 SD 卡而不是设备存储中写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆