java - 自 API 26 起,如何从现有文件 URI 保存/覆盖文件?

标签 java android database performance filesystems

所以我正在使用一个图像捕获库,它为我提供了临时缓存文件的 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/

相关文章:

php - 将以下 MySQL 查询转换为等效的 Codeigniter

php - 从html到mysql数据库的基本输入

java - Spring LDAP 返回相同且不正确的 objectSid

java - 如何在 Spring Boot 应用程序中关闭客户端 sse 连接

Android 自定义键盘方向符号/qwerty

Android dx 生成错误的校验和 dex 文件

android水平和垂直recyclerview项目装饰

java - 集成 Paytm 支付网关 Android

java - c3p0 Java 数据库池,故障转移配置

java - 找不到类 [org.apache.derby.jdbc.ClientDriver]。尝试连接到数据库时