2013-05-31 148 views
0

我在保存位图到手机存储时遇到问题。看起来好像我无法创建新文件。我得到异常 - >java.io.Exception:打开失败:EAccess(权限被拒绝)在java.io.File.createNewFile(File.java:940)Android:将位图保存到手机存储

正在使用的strFileName是* /存储/ sdcard0/SpenSDK /图片/ 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

你忘记了WRITE_EXTERNAL_STORAGE权限?

你的硬编码路径是否真的指向SD卡?

1

您需要WRITE_EXTERNAL_STORAGE权限。你也可以去掉createNewFile。如果该文件不存在,将创建

+0

他为什么要摆脱createNewFile。询问我的澄清。这个“正在使用的strFileName是*/storage/sdcard0/SpenSDK/images/testimage_00”的bcoz? – Raghunandan

+0

因为它是无用 – Blackbelt

+0

同意@blackbelt,但他有这个返回(bSuccess1 && bSuccess2 && bSuccess3); – Raghunandan

1

除了许可, ,你应该通过使用方法得到sdcard的路径

Environment.getExternalStorageDirectory(); 

并追加需要的目录到返回的路径。