2013-08-06 108 views
1

我想下載一個圖像文件並覆蓋現有文件(如果存在)。下載圖像文件並替換現有的圖像文件

但它並不取代現有的文件。

public static String saveBitmap(String url, String fileName, Context context, 
     boolean deleteExisting) { 
    File cacheDir; 
    if (android.os.Environment.getExternalStorageState().equals(
      android.os.Environment.MEDIA_MOUNTED)) 
     cacheDir = context.getDir("images", Context.MODE_PRIVATE); 
    else 
     cacheDir = context.getCacheDir(); 
    if (!cacheDir.exists()) 
     cacheDir.mkdirs(); 

    File f = new File(cacheDir, fileName + ".png"); 
    Bitmap bitmap = null; 
    // Is the bitmap in our cache? 
    if (f.exists()) { 
     bitmap = BitmapFactory.decodeFile(f.getPath()); 
    } 
    if (bitmap != null && !deleteExisting) 
     return f.getPath(); 
    else { 
     // Nope, have to download it 
     try { 
      InputStream input = new URL(url).openConnection().getInputStream(); 
      bitmap = BitmapFactory.decodeStream(new FlushedInputStream(input)); 
      // save bitmap to cache for later 
      writeFile(bitmap, f); 
      return f.getPath(); 
     } catch (FileNotFoundException ex) { 
      ex.printStackTrace(); 
      return null; 
     } catch (Exception e) { 
      // TODO: handle exception 
      e.printStackTrace(); 
      return null; 
     } 
    } 
} 
+0

你嘗試過什麼解決問題添加此權限嗎?有沒有例外? – Egor

+0

沒有例外,下載工作正常,但如果我在下載文件夾之前清空文件夾,所有圖像文件變爲空白 – meh

+0

確定,然後描述您已採取措施解決問題。 – Egor

回答

3

去通過下面的代碼,用於存儲文件

private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) { 

File direct = new File(Environment.getExternalStorageDirectory() + "/DirName"); 

if (!direct.exists()) { 
    File wallpaperDirectory = new File("/sdcard/DirName/"); 
    wallpaperDirectory.mkdirs(); 
    } 

    File file = new File(new File("/sdcard/DirName/"), fileName); 
    if (file.exists()) 
     file.delete(); 
    try { 
     FileOutputStream out = new FileOutputStream(file); 
     imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out); 
     out.flush(); 
     out.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 
0

您是否嘗試過的權限,如果沒有則在manifest

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"