所以我正在使用一个图像捕获库,它为我提供了临时缓存文件的 URI。然后我想将该文件保存在我的应用程序的文件目录中作为“/avatar.jpg”,覆盖任何现有的“avatar.jpg”文件。到目前为止,这是我尝试实现目标的代码:
File file = new File(tempImagePath);
File avatarFile = new File(getFilesDir(), "avatar.jpg");
file.renameTo(avatarFile);
但是,这不会覆盖任何现有的“avatar.jpg”文件。我注意到文件系统 API 发生了一些变化,例如引入 FileProvider所以我并不是实现我所需要的最快/最有效的方法。
最佳答案
我相信您可以检查目标文件是否存在,如果存在则将其删除,然后将缓存的图像文件移动到所需的目的地。
// Check if file exists, and delete it.
File avatarFile = new File(getFilesDir(), "avatar.jpg");
if (avatarFile.exists())
avatarFile.delete();
并阅读this answer关于如何将文件移动到所需的目的地。另请阅读Java I/O lesson ,那里有一些有用的教程。
附注:您也可以尝试get the Bitmap
of the image file您正在尝试另存为头像,并将其写入目标文件。阅读 this answer了解更多信息。
关于java - 自 API 26 起,如何从现有文件 URI 保存/覆盖文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47209059/