简体   繁体   English

从API 26开始,如何从现有文件URI中保存/覆盖文件?

[英]How to save/overwrite a file from an existing file URI as of API 26?

So I'm using an image capture library that gives me a URI to a temporary cached file. 因此,我正在使用一个图像捕获库,该库为我提供了一个到临时缓存文件的URI。 I want to then save that file in my app's file directory as "/avatar.jpg", overwriting any existing "avatar.jpg" file. 然后,我想将该文件保存为我的应用程序文件目录中的“ /avatar.jpg”,覆盖所有现有的“ avatar.jpg”文件。 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. 但是,这不会覆盖任何现有的“ avatar.jpg”文件。 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. 我注意到文件系统API进行了几处更改,例如FileProvider的引入,因此我并不是实现我所需的最快/最有效的方法。

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. 另外,阅读Java I / O课程 ,那里有一些有用的教程。

PS: 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. PS:您还可以尝试获取要保存为头像的图像文件的Bitmap ,并将其写入目标文件。 Read this answer for more info on that. 阅读此答案以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM