2016-03-04 35 views
0

我试图挽救从互联网上下载的文件用下面的代码Android的 - 不能保存文件到存储

public static String saveToSdCard(Bitmap bitmap, String filename) { 

    String stored = null; 

    File sdcard = Environment.getExternalStorageDirectory() ; 

    File folder = new File(sdcard.getAbsoluteFile(), ".tanks"); 
    boolean success = true; //the dot makes this directory hidden to the user 

    if (!folder.exists()) { 
     success = folder.mkdir(); 
    } 

    if (success) { 
     File file = new File(folder.getAbsoluteFile(), filename + ".jpg") ; 
     if (file.exists()) 
      return stored ; 

     try { 
      FileOutputStream out = new FileOutputStream(file); 
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); 
      out.flush(); 
      out.close(); 
      stored = "success"; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

    return stored; 
} 

但在运行时我得到错误,如

03-04 20:42:51.080 8972-8972/com.example.me.demo2 E/BitmapFactory:无法解码流:java.io.FileNotFoundException: /storage/emulated/0/.tanks/4a100abb-0e55-4062-8c37-f11f4189e618.jpg:open失败:ENOENT(没有这样的文件或目录)

在我的应用程序清单文件,我添加的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

但是,当我启动的应用程序没有警告,要求授予的权限。

我做错了什么?

+0

https://stackoverflow.com/questions/32635704/cant-get-the-permission – CommonsWare

回答

0

尝试删除该文件夹并手动创建它。根据您的代码,

File tempFolder = new File(sdcard.getAbsoluteFile(), ".tanks"); 
tempFolder.mkdirs(); 
if (success) { 
    File file = new File(tempFolder, filename + ".jpg") ; 
    ... 
}