【发布时间】:2016-10-17 13:12:50
【问题描述】:
我需要在 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() 相同的结果。
知道代码出了什么问题吗?
谢谢
【问题讨论】:
-
也许是you do not have runtime permissions implemented。除此之外,永远不要在没有记录的情况下捕获异常。将
e作为第三个参数添加到您的Log.d()调用中,然后使用 LogCat 检查与您的崩溃相关的 Java 堆栈跟踪。 -
你能告诉我们堆栈跟踪吗?
-
if (!dir.exists() || !dir.isDirectory()) dir.mkdirs();。糟糕代码的好例子。首先,如果它确实不是目录,则文件 mkdirs 不会将该文件转换为目录。其次,您应该检查 mkdirs 的返回值,因为它可能会失败。顺便说一句。 -
试试这个它可能是工作 stackoverflow.com/a/41221852/5488468
-
好问题!有帮助