Java 对文件进行重命名操作(rename)

在传统的 java.io.File 类中有这样一个方法

boolean java.io.File.renameTo(File dest)

以下是关于方法的说明:

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.

Note that the java.nio.file.Files class defines the move method to move or rename a file in a platform independent manner.

 其中对该方法的一些缺陷进行了说明。如:

1. 具有一定平台依赖性;

2. 无法从一个文件系统移动到另一个文件系统;

3. 可能不是原子性的;

4. 如果目标 File 已经存在,可能无法成功

而且尽可能检查返回值确保重命名操作成功。

 

同时,还推荐了 java.nio.file.Files 类的 move 方法

Path java.nio.file.Files.move(Path source, Path target, CopyOption... options) throws IOException

该方法源自 JDK 1.7。该方法抛出异常,因此需要 catch 处理。以下是该方法的一个使用例子。

File sourceFile = new File(pathname + File.separator + oldName);
File targetFile = new File(pathname + File.separator + newName);
Path source = sourceFile.toPath();
Path target = targetFile.toPath();
try {
	Files.move(source, target);
} catch (IOException e) {
	e.printStackTrace();
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罐装面包

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值