Android RenameTo留空文件 [英] Android RenameTo leaves empty file

查看:316
本文介绍了Android RenameTo留空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能帮我吗? renameTo()留空的旧文件.因此,我在文件系统中看到2个具有新名称和旧名称的文件.旧文件的大小为0.如果我在重命名后删除了旧文件,则说该文件在文件系统中时不存在.

Could you please help me. renameTo() leaves empty old file. So I see 2 files in file system with new name and old name. The size of old file is 0. If I delete old file after renaming it says that file does not exist while staying in file system.

目录的绝对路径为:

/storage/sdcard0/DCIM/Camera

我的代码:

       String dir = oldpath.substring(0, oldpath.lastIndexOf("/"));

        File directory = new File(dir);
        File from      = new File(directory, oldfilename);
        File to        = new File(directory, newname);

        renamed = from.renameTo(to);

推荐答案

如果另一个文件打开了文件,RenameTo将保留原始文件的空副本.

RenameTo leaves an empty copy of the original file if the file is opened by another process.

例如,我想在DownloadManager完成下载后重命名文件.在下载之后但关闭文件之前,DownloadManager显然会通知BroadcastReceivers.这导致onReceive中的renameTo留下一个空副本.为了解决这个问题,我不得不让BroadcastReceiver等待半秒钟再重命名文件.

For example, I wanted to rename a file after the DownloadManager finished downloading it. The DownloadManager apparently notifies the BroadcastReceivers after the download, but before closing the file. This caused the renameTo in the onReceive to leave an empty copy. To solve this problem, I had to make the BroadcastReceiver to wait half a second before renaming the file.

这篇关于Android RenameTo留空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆