我正在尝试将图像从应用程序本地数据文件夹保存到外部存储。我的 list 包含以下内容(在 list 的应用程序标记之前):
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/>
当我尝试以下操作时
try {
InputStream in = new FileInputStream(filePath);
File outPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File outFile = new File(outPath, "mypicture.jpg");
//try fails at this line
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
e.printStackTrace();
}
我收到这个错误:
java.io.FileNotFoundException: /storage/emulated/0/Pictures/mypicture.jpg: open failed: EACCES (Permission denied)
我也尝试了一个稍微不同的输出路径:
String sdCardPath = Environment.getExternalStorageDirectory() + "/MyFolder";
new File(sdCardPath).mkdirs();
File outFile = new File(sdCardPath, "mypicture.jpg");
但这也给我一个错误:
java.io.FileNotFoundException: /storage/emulated/0/MyFolder/mypicture.jpg: open failed: ENOENT (No such file or directory)
该设备运行的是 Android 4.4.2,因此不需要在运行时请求权限(据我所知,它不能请求它们)。
为了允许将文件保存到外部存储,是否还有其他可能缺失的东西?
最佳答案
问题的原因是通过 gradle 引入的外部库有自己的 list 请求 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18">
我自己的 list 仅在未包含 maxSdkVersion="18"时有效,因此添加该参数的 list 合并导致了此错误。我的解决方案是将我自己的 list 更改为:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="23" tools:replace="android:maxSdkVersion" />
我假设 maxSdkVersion="18"意味着任何运行 SDK 19-22 的设备都无法拥有此权限(23+ 能够在运行时请求它)。
关于android - WRITE_EXTERNAL_STORAGE 不适用于 Lollipop ,即使它已在 list 中设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41552251/