我正在尝试下载图像文件并覆盖现有文件(如果存在)。
但它不会替换现有文件。
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;
}
}
}