2016-03-04 28 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") ; 
    ... 
}