如何在外部SD卡中而不是在设备存储中写入文件? [英] How to write a file in external sd card and not in device storage?
问题描述
我尝试过:
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.
推荐答案
On Android 4.4+, you have two main options:
-
使用
getExternalFilesDirs()
,getExternalCacheDirs()
或getExternalMediaDirs()
(请注意复数),Context
上的所有方法.如果它们返回2个以上的位置,则第二个和后面的位置是可移动存储上的位置,您的应用可以在没有任何权限的情况下读取和写入这些位置.
Use
getExternalFilesDirs()
,getExternalCacheDirs()
, orgetExternalMediaDirs()
(note the plural), all methods onContext
. 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
和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屋!