如何 save/overwrite 从 API 26 开始的现有文件 URI 中的文件?
How to save/overwrite a file from an existing file URI as of API 26?
所以我正在使用一个图像捕获库,它为我提供一个临时缓存文件的 URI。然后我想将该文件作为“/avatar.jpg”保存在我的应用程序的文件目录中,覆盖任何现有的 "avatar.jpg" 文件。到目前为止,这是我尝试实现目标的代码:
File file = new File(tempImagePath);
File avatarFile = new File(getFilesDir(), "avatar.jpg");
file.renameTo(avatarFile);
但是,这不会覆盖任何现有的 "avatar.jpg" 文件。我注意到文件系统 API 的一些变化,例如 FileProvider 的引入,所以我不是 fastest/most 完成我需要的有效方法。
我相信您可以检查目标文件是否存在,如果存在则将其删除,然后将缓存的图像文件移动到所需的目标。
// Check if file exists, and delete it.
File avatarFile = new File(getFilesDir(), "avatar.jpg");
if (avatarFile.exists())
avatarFile.delete();
并阅读 this answer on how to move the file to the desired destination. Also, read the Java I/O lesson,那里有一些有用的教程。
P.S.: 您也可以尝试 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 了解更多信息。
所以我正在使用一个图像捕获库,它为我提供一个临时缓存文件的 URI。然后我想将该文件作为“/avatar.jpg”保存在我的应用程序的文件目录中,覆盖任何现有的 "avatar.jpg" 文件。到目前为止,这是我尝试实现目标的代码:
File file = new File(tempImagePath);
File avatarFile = new File(getFilesDir(), "avatar.jpg");
file.renameTo(avatarFile);
但是,这不会覆盖任何现有的 "avatar.jpg" 文件。我注意到文件系统 API 的一些变化,例如 FileProvider 的引入,所以我不是 fastest/most 完成我需要的有效方法。
我相信您可以检查目标文件是否存在,如果存在则将其删除,然后将缓存的图像文件移动到所需的目标。
// Check if file exists, and delete it.
File avatarFile = new File(getFilesDir(), "avatar.jpg");
if (avatarFile.exists())
avatarFile.delete();
并阅读 this answer on how to move the file to the desired destination. Also, read the Java I/O lesson,那里有一些有用的教程。
P.S.: 您也可以尝试 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 了解更多信息。