我需要在 android 上保存来自相机的图像。我在清单中使用了写外部存储权限,我正在使用这段代码
File dir = new File(Environment.getExternalStorageDirectory(), "Test");
if (!dir.exists() || !dir.isDirectory())
dir.mkdirs();
String path = dir.getAbsolutePath();
Log.d(TAG, path); //log show the path
File file = new File(dir.getAbsolutePath() + "/Pic.jpg");
Log.d(TAG, file.getAbsolutePath()); //again path is shown here
outStream = new FileOutputStream(file);
outStream.write(bytes);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + bytes.length); //fail here
} catch (FileNotFoundException e) {
Log.d(TAG, "not done"); //error is here (this exception is thrown)
} catch (IOException e) {
Log.d(TAG, "not");
} finally { }
我也尝试了 mkdir() 而不是 mkdirs() 相同的结果。
知道代码出了什么问题吗?
谢谢
原文由 lallous34 发布,翻译遵循 CC BY-SA 4.0 许可协议
对于那些没有像我这样经验丰富的人。我与这个问题作斗争,脱发有一段时间了。我的目标是 api 21(出于兼容性考虑),它在 lollipop 上工作,但在 marshmallow 上它不会创建目录。我确实在清单中拥有“使用”权限,但它仍然无法正常工作。显然在 Marshmallow 中,当您使用 Android Studio 安装时,它从不询问您是否应该授予它许可,它只是安静地失败,就像您拒绝它一样。您必须进入“设置”、“应用程序”,选择您的应用程序并打开权限开关。