Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download an image file and replace existing image file

Tags:

android

I am trying to download an image file and override and existing file if it exists.

But it doesn't replace the existing file.

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;
        }
    }
}
like image 920
meh Avatar asked Jan 25 '26 19:01

meh


1 Answers

Go through following code for storing file

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();
    }

}
like image 57
mdDroid Avatar answered Jan 28 '26 08:01

mdDroid