o19830015 2013-02-20 06:08 采纳率: 12.5%
浏览 3065

重命名一个已存在的文件

有两个文件:

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

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

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

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

请帮忙解决一下,谢谢。

  • 写回答

2条回答 默认 最新

  • loFataMer 2013-02-20 06: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也可以。

    评论

报告相同问题?

悬赏问题

  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题