0

So I'm using an image capture library that gives me a URI to a temporary cached file. I want to then save that file in my app's file directory as "/avatar.jpg", overwriting any existing "avatar.jpg" file. So far, this is my code for attempting to accomplish my goal:

File file = new File(tempImagePath);

File avatarFile = new File(getFilesDir(), "avatar.jpg");
file.renameTo(avatarFile);

However, this does not overwrite any existing "avatar.jpg" file. I've noticed several changes to the filesystem API such as the introduction of FileProvider so I'm not what the fastest/most efficient way of accomplishing what I require is.

Mauker
  • 11,237
  • 7
  • 58
  • 76
BeardMagician
  • 647
  • 13
  • 26

1 Answers1

1

I believe you can just check if the destination file exists, delete it if it's there and move the cached image file to the desired destination.

// Check if file exists, and delete it.
File avatarFile = new File(getFilesDir(), "avatar.jpg");
if (avatarFile.exists())
    avatarFile.delete();

And read this answer on how to move the file to the desired destination. Also, read the Java I/O lesson, there are some useful tutorials there.

P.S.: You could also try to get the Bitmap of the image file you're trying to save as an avatar, and write it on the destination file. Read this answer for more info on that.

Mauker
  • 11,237
  • 7
  • 58
  • 76
  • So file.delete() simply just doesn't work for me. I've also tried Context.deleteFile() and that also does not work. The methods return true but the file still persists. – BeardMagician Nov 10 '17 at 02:40
  • Are you setting the ImageView resource as an URI by any chance? – Mauker Nov 10 '17 at 03:07
  • No, I'm loading it in from a file via Glide. Even on app restarts the old file persists – BeardMagician Nov 10 '17 at 03:10
  • Try to disable Glide's cache, that might be the problem. Try to use `.diskCacheStrategy(DiskCacheStrategy.NONE)` and `.skipMemoryCache( true )` when loading the image. – Mauker Nov 10 '17 at 03:13
  • Glide.with(this) .load(FileUtils.getUserAvatarFile(this)) .into(headerProfileView); is my code; there's no .diskCacheStrategy or .skipMemoryCache method in the builder – BeardMagician Nov 10 '17 at 03:19
  • There should be. Like: `Glide.with(this) .load(FileUtils.getUserAvatarFile(this)).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache( true ).into(headerProfileView);` – Mauker Nov 10 '17 at 03:35
  • If neither of that works, try: `mContext.getContentResolver().delete(fileToDeleteUri, null, null);` – Mauker Nov 10 '17 at 08:44