2 o19830015 o19830015 于 2013.02.20 14:08 提问

重命名一个已存在的文件

有两个文件:

File src = new File("loc/xyz.mp3")File dst=new File("loc/xyz1.mp3")

现在我想将xyz.mp3重命名为dst,同时删除src文件,怎么才能实现?我试过的代码:

src.delete();
dst.renameTo(src);

在应用的背景中异步运行,第一次执行时成功了,但是第二次就崩溃了。

请帮忙解决一下,谢谢。

3个回答

sasuke38
sasuke38   2013.02.21 09:47
已采纳
new File("loc/xyz.mp3").renameTo(new File("loc/xyz1.mp3"));
loFataMer
loFataMer   2013.02.20 14:33

根据文档说明:

Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

在AsyncTask中,不能保证srcdst。检测一下src.exists() && dst.exists()可能帮助你避免错误。 使用deleteOnExit也可以。

ce_la_vie
ce_la_vie   2013.02.20 16:37
new File("loc/xyz1.mp3").renameTo(new File("loc/xyz.mp3"));
Csdn user default icon
上传中...
上传图片
插入图片