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 已经存在,可能无法成功

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

扫描二维码关注公众号,回复: 11929430 查看本文章

同时,还推荐了 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();
}

猜你喜欢

转载自blog.csdn.net/qq_39291919/article/details/108829922