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

查看:95
本文介绍了如何在外部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()(请注意复数),Context上的所有方法.如果它们返回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_DOCUMENT ,以允许用户选择将某些内容放置在何处,用户可以在其中选择可移动存储(或Google云端硬盘,DropBox或使用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天全站免登陆