我在将位图保存到手机存储时遇到问题。好像我无法创建新文件。我得到例外 - > java.io.Exception:打开失败:java.io.File.createNewFile(File.java:940)上的EAccess(权限被拒绝)。
正在使用的strFileName是* / storage / sdcard0 / SpenSDK / images / testimage_00 *
奇怪的是,这段代码正在以前的项目中运行。我想知道是否有人有想法为什么抛出这个异常。
以下是以PNG格式保存到手机存储空间的代码。
private boolean saveBitmapPNG(String strFileName, Bitmap bitmap){
if(strFileName==null || bitmap==null){
System.out.println("!!!error saving image - false in SavePNG - NAME OR BITMAP");
return false;
}
boolean bSuccess1 = false;
boolean bSuccess2;
boolean bSuccess3;
File saveFile = new File(strFileName);
if(saveFile.exists()) {
if(!saveFile.delete())
System.out.println("!!!error saving image - false in SavePNG - could not delete existing");
return false;
}
try {
bSuccess1 = saveFile.createNewFile();//----------------->EXCEPTION IS THROWN HERE
} catch (IOException e1) {
System.out.println("!!!error saving image - false in SavePNG - could not create new file");
e1.printStackTrace();
}
OutputStream out = null;
try {
out = new FileOutputStream(saveFile);
bSuccess2 = bitmap.compress(CompressFormat.PNG, 100, out); //----------------->EXCEPTION IS THROWN HERE
} catch (Exception e) {
e.printStackTrace();
System.out.println("!!!error saving image - false in SavePNG - could not compress");//-->3
bSuccess2 = false;
}
try {
if(out!=null) //----------------->OUT == null here
{
out.flush();
out.close();
bSuccess3 = true;
}
else
System.out.println("!!!error saving image - false in SavePNG - could not close");//-->4
bSuccess3 = false;
} catch (IOException e) {
e.printStackTrace();
System.out.println("!!!error saving image - false in SavePNG - could not close (exception");
bSuccess3 = false;
}finally
{
if(out != null)
{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return (bSuccess1 && bSuccess2 && bSuccess3);
}
答案 0 :(得分:1)
您需要WRITE_EXTERNAL_STORAGE
权限。你也可以摆脱createNewFile。如果文件不存在将被创建
答案 1 :(得分:1)
在清单文件中添加此权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
查看链接以获取更多信息
http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE
答案 2 :(得分:1)
除了以前答案中给出的权限之外,您还应该使用方法
获取SD卡的路径Environment.getExternalStorageDirectory();
并将所需目录附加到返回路径。
答案 3 :(得分:0)
您是否忘记了WRITE_EXTERNAL_STORAGE
权限?
您的硬编码路径是否真的指向SD卡?