java中给文件改名

1.File   oldf   =   new   File(oldFileName);
File   newf   =null;

if   (oldf   !=   null)   {
    newf   =   new   File(newFileName);
    oldf.renameTo(newf);
}

 

 

2. 以前我一直以为File#renameTo(File)方法与OS下面的 move/mv 命令是相同的,可以达到改名、移动文件的目的。不过后来经常发现问题:File#renameTo(File)方法会返回失败(false),文件没有移动,又查不出原因,再后来干脆弃用该方法,自己实现一个copy方法,问题倒是再也没有出现过。

  昨天老板同学又遇到这个问题,File#renameTo(File)方法在windows下面工作的好好的,在linux下偶尔又失灵了。回到家我扫了一遍JDK中File#renameTo(File)方法的源代码,发现它调用的是一个本地的方法(native method),无法再跟踪下去。网上有人说该方法在window下是正常的,在linux下面是不正常的。这个很难说通,SUN不可能搞出这种平台不一致的代码出来啊。

  后面在SUN的官方论坛上看到有人提到这个问题“works on windows, don't work on linux”,后面有人回复说是“file systems”不一样。究竟怎么不一样呢?还是没有想出来...

  后面在一个论坛里面发现了某人关于这个问题的阐述:

  In the Unix'esque O/S's you cannot renameTo() across file systems. This behavior is different than the Unix "mv" command. When crossing file systems mv does a copy and delete which is what you'll have to do if this is the case.

  The same thing would happen on Windows if you tried to renameTo a different drive, i.e. C: -> D:

  终于明白咯。

  做个实验:

  

以下是代码片段:
1 File sourceFile = new File("c:/test.txt");
  2 File targetFile1 = new File("e:/test.txt");
  3 File targetFile2 = new File("d:/test.txt");
  4 System.out.println("source file is exist? " + sourceFile.exists() + ", source file => " + sourceFile);
  5 System.out.println(targetFile1 + " is exist? " + targetFile1.exists());
  6 System.out.println("rename to " + targetFile1 + " => " + sourceFile.renameTo(targetFile1));
  7 System.out.println("source file is exist? " + sourceFile.exists() + ", source file => " + sourceFile);
  8 System.out.println(targetFile2 + " is exist? " + targetFile2.exists());
  9 System.out.println("rename to " + targetFile2 + " => " + sourceFile.renameTo(targetFile2));
  结果:

  

以下是代码片段:
1 source file is exist? true, source file => c:\test.txt
  2 e:\test.txt is exist? false
  3 rename to e:\test.txt => false
  4 source file is exist? true, source file => c:\test.txt
  5 d:\test.txt is exist? false
  6 rename to d:\test.txt => true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值