Java 重命名或移动文件
本文我们看看java中如何重命名或移动文件,首先使用jdk6,然后jdk7的nio以及第三方库实现。
使用jdk6
使用jdk6方案:
@Test
public void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt");
boolean isMoved = fileToMove.renameTo(new File("src/test/resources/movedFile_jdk6.txt"));
if (!isMoved) {
throw new FileSystemException("src/test/resources/movedFile_jdk6.txt");
}
}
本例中,要移动的文件及目标目录都要存在。
请注意,如果对原文件或目标文件没有写权限,renameTo()会抛SecurityException 异常;如果target参数为null,则抛 NullPointerException 异常。没有抛异常,你需要检查返回值判断是否成功。
使用jdk7
让我们看如何使用jdk7做相同的事情:
@Test
public void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
Path fileToMovePath =
Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt"));
Path targetPath = Paths.get("src/main/resources/");
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
}
在jdk7中nio包做了重大升级,增加了Path接口,提供了便利的操作文件系统构件方法。与上面的示例类似,文件和目标目录应该存在。
使用guava
Guava解决方案如下:
@Test
public void givenUsingGuava_whenMovingFile_thenCorrect()
throws IOException {
File fileToMove = new File("src/test/resources/fileToMove.txt");
File destDir = new File("src/test/resources/");
File targetFile = new File(destDir, fileToMove.getName());
com.google.common.io.Files.move(fileToMove, targetFile);
}
还是一样,文件和目标目录必须存在。
使用apache commons io
最后,我们看下apache commons io的实现方式,可能是最简单的方法:
@Test
public void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
FileUtils.moveFile(
FileUtils.getFile("src/test/resources/fileToMove.txt"),
FileUtils.getFile("src/test/resources/fileMoved.txt"));
}
一行代码,当然可以移动或重命名————依赖目标目录是否相同。
另外还有方法特别为了移动,也提供参数控制如果目标目录不存在会创建目标目录:
@Test
public void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
FileUtils.moveFileToDirectory(
FileUtils.getFile("src/test/resources/fileToMove.txt"),
FileUtils.getFile("src/main/resources/"), true);
}
总结
上面我们看了几种方法实现文件重命名,当然,如果目标目录不同,就实现了文件移动。