【发布时间】:2013-06-01 07:01:44
【问题描述】:
在我的 Android 项目中,我试图将位图保存到给定位置的 SD 卡。
当我运行这个时,我每次都会收到一个IOException,说权限被拒绝。这是关于创建 FileOutputStream。
这让我相信我缺少权限,但我包含了READ and WRITE_EXTERNAL_STORAGE。它们在我的 uses-sdk 块之前声明并且在应用程序块之外。我还将 read/write 文本发送到我的应用程序其他地方的文件中,并且效果很好。我当前的代码被修改以匹配我在网上找到的几个解决方案,但我无法成功保存bitmap 文件。
如果有人能指出我的错误,我将非常感激。
ImageView imageView = (ImageView) findViewById(R.id.new_pnm_pic);
Bitmap bm = (Bitmap)data.getExtras().get("data");
imageView.setImageBitmap(bm);
String outPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recruits";
try {
File d = new File(outPath);
if (!d.exists())
d.mkdirs();
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
String currentTime = sd.format(new Date());
File file = new File(outPath+'/'+currentTime+".jpg");
FileOutputStream fOut = new FileOutputStream(file.getPath());
bm.compress(Bitmap.CompressFormat.JPEG, 50, fOut);
fOut.flush();
fOut.close();
}
catch(IOException ioe){
Toast.makeText(this, "Nice try but didn't work", Toast.LENGTH_SHORT).show();
}
【问题讨论】:
-
如果你用 Environment.getExternalStorageDirectory().toString() + "Recruits" 定义你的 outPath 是否有效?我对 getAbsolutePath() 有类似的问题,解决了它。做一个日志。在 logcat 中查看完整路径。
-
你是在模拟器上运行的吗
-
我把 outPath 改成了 Environment.getExternalStorageDirectory().toString() + "/Recruits";并使用 Logs 进行测试以查看我的文件使用以下路径 W//mnt/sdcard/Recruits/2013-06-01-17-26-50.jpg(23309) 当我在创建 FileOutputStream 后尝试测试时,日志没有显示,这意味着这是异常所在。我还尝试使用备用构造函数 FileOutputStream(File) ,但仍然出现异常。山姆:我在我的设备上运行这个
-
我也刚刚发现了如何检查异常消息并用它来确定问题是“权限被拒绝”,但我在程序的其他地方读/写文本文件,效果很好
标签: android file-io bitmap compression ioexception