我正在尝试将应用程序本地数据文件夹中的图像保存到外部存储.我的清单包含以下内容(在清单的应用程序标记之前):
<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,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引入的外部库,其具有其自己的清单请求< uses-permission android:name =“android.permission.WRITE_EXTERNAL_STORAGE”android:maxSdkVersion =“18”>
如果没有包含maxSdkVersion =“18”,那么我自己的清单才有效,因此添加该参数的清单合并会导致此错误.我的解决方案是将我自己的清单改为:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="23" tools:replace="android:maxSdkVersion" />
我假设maxSdkVersion =“18”意味着运行SDK 19-22的任何设备都没有此权限(23可以在运行时请求它).