【问题标题】:How to save/overwrite a file from an existing file URI as of API 26?从 API 26 开始,如何从现有文件 URI 保存/覆盖文件?
【发布时间】:2018-04-22 20:56:49
【问题描述】:

所以我使用了一个图像捕获库,它为我提供了一个临时缓存文件的 URI。然后我想将该文件保存在我的应用程序的文件目录中作为“/avatar.jpg”,覆盖任何现有的“avatar.jpg”文件。到目前为止,这是我尝试实现目标的代码:

File file = new File(tempImagePath);

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

但是,这不会覆盖任何现有的“avatar.jpg”文件。我注意到文件系统 API 发生了一些变化,例如引入了 FileProvider,所以我不是完成我需要的最快/最有效的方法。

【问题讨论】:

    标签: java android database performance filesystems


    【解决方案1】:

    我相信您可以检查目标文件是否存在,如果存在则将其删除并将缓存的图像文件移动到所需的目标。

    // 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,那里有一些有用的教程。

    P.S.:您也可以尝试get the Bitmap of the image file您尝试另存为头像,并将其写入目标文件。阅读this answer了解更多信息。

    【讨论】:

    • 所以 file.delete() 根本不适合我。我也尝试过 Context.deleteFile() 但这也不起作用。这些方法返回 true,但文件仍然存在。
    • 您是否将 ImageView 资源设置为 URI?
    • 不,我正在通过 Glide 从文件中加载它。即使在应用重新启动时,旧文件仍然存在
    • 尝试禁用 Glide 的缓存,这可能是问题所在。加载图片时尝试使用.diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache( true )
    • Glide.with(this) .load(FileUtils.getUserAvatarFile(this)) .into(headerProfileView);是我的代码;构建器中没有 .diskCacheStrategy 或 .skipMemoryCache 方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 2022-01-25
    • 2018-08-22
    • 2019-02-28
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    相关资源
    最近更新 更多