Android 6.0写入外部SD卡 [英] Android 6.0 Write to external SD Card
问题描述
我已尝试将所有内容写在Android 6.0上的外部SD卡上,但无法在上面写.
I tried everything to write on external SD card on Android 6.0, but I am not able to write on it.
我对stackoverflow进行了研究,发现了很多东西,但是没有用.这是我的代码
I did research on stackoverflow and found lot of things but none works. Here is my code
String extPath = System.getenv("SECONDARY_STORAGE") + "/Android/data/com.gvm.externalstorage.externalstoragetest/";
File file = new File(extPath,"myFiles");
if (!file.exists()) {
boolean dirResult = file.mkdirs();
Log.e("Directory Exist", dirResult + " Directory created");
} else {
Log.e("Directory Exist", "Exist");
Log.e("Direcotry Path",file.getAbsolutePath());
}
//String displayname = fileName.replace("%20", " ");
File outputFile = new File(file, "mytest5.txt");
outputFile.createNewFile();
此代码在Android 5.0上有效,但在Android 6.0上无效.
This code works on Android 5.0 but not on Android 6.0.
然后我也尝试了该路径,这给了我权限错误,我还为运行时权限设置了所有权限和托管代码.
Then I tried this path as well, and that gives me permission error, I have set all permission and managed code for runtime permission as well.
/mnt/media_rw/6AC9-083B
File write failed: java.io.IOException: open failed: EACCES (Permission denied)
如果有人可以帮助我,那将是非常棒的事情,因为自最近三天以来我一直在尝试这样做.
If anyone can help me it would be great as I am trying this since last 3 days.
谢谢, Anvesh
Thanks, Anvesh
推荐答案
经过长时间的努力,我找到了解决方案.在Android 6.0中,不会始终使用以下命令为您提供SD卡路径:
After long hard work I figured out a solution. In Android 6.0 it's not going to give you SD Card path always using this:
System.getenv("SECONDARY_STORAGE")
或这个
Environment.getExternalStorageDirectory()
所以我使用此文件检索了外部SD卡路径
So I retrieved external SD Card path using this
File[] fs = context.getExternalFilesDirs(null);
String extPath = "";
// at index 0 you have the internal storage and at index 1 the real external...
if (fs != null && fs.length >= 2)
{
extPath = fs[1].getAbsolutePath();
Log.e("SD Path",fs[1].getAbsolutePath());
}
其余所有内容均应保持许可状态.
Rest everything will remain same for permission and all.
感谢那些帮助过我的人.
Thanks to those who helped me.
这篇关于Android 6.0写入外部SD卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!