1. Overview
1.概述
In this quick tutorial, we’re going to look at renaming / moving a File in Java.
在这个快速教程中,我们将学习在Java中重命名/移动一个文件。
We’ll first look into using the Files and Path classes from NIO, then the Java File class, Google Guava, and finally the Apache Commons IO library.
我们将首先研究使用NIO的Files和Path类,然后是JavaFile类、Google Guava,最后是Apache Commons IO库。
This article is part of the “Java – Back to Basic” series here on Baeldung.
本文是“Java – Back to Basic“系列的一部分,位于Baeldung。
2. Setup
2.设置
In the examples, we’ll use the following setup, which consists of 2 constants for the source and destination file name and a clean-up step to be able to run the tests multiple times:
在例子中,我们将使用以下设置,其中包括源文件和目标文件名的2个常量和一个清理步骤,以便能够多次运行测试。
private final String FILE_TO_MOVE = "src/test/resources/originalFileToMove.txt";
private final String TARGET_FILE = "src/test/resources/targetFileToMove.txt";
@BeforeEach
public void createFileToMove() throws IOException {
File fileToMove = new File(FILE_TO_MOVE);
fileToMove.createNewFile();
}
@AfterEach
public void cleanUpFiles() {
File targetFile = new File(TARGET_FILE);
targetFile.delete();
}
3. Using the NIO Paths and Files Classes
3.使用NIO的Paths和FilesClasses
Let’s start by using the Files.move() method from the Java NIO package:
让我们从使用Java NIO包中的Files.move()方法开始。
@Test
public void givenUsingNio_whenMovingFile_thenCorrect() throws IOException {
Path fileToMovePath = Paths.get(FILE_TO_MOVE);
Path targetPath = Paths.get(TARGET_FILE);
Files.move(fileToMovePath, targetPath);
}
In JDK7 the NIO package was significantly updated, and the Path class added. This provides methods for convenient manipulation of File System artifacts.
在JDK7中,NIO包被大幅更新,并添加了Path类。这提供了方便操作文件系统工件的方法。
Note that both the file and the target directory should exist.
注意,文件和目标目录都应该存在。
4. Using the File Class
4.使用文件类
Let’s now look at how we can do the same using the File.renameTo() method:
现在让我们看看我们如何使用File.renameTo()方法来做同样的事情:。
@Test
public void givenUsingFileClass_whenMovingFile_thenCorrect() throws IOException {
File fileToMove = new File(FILE_TO_MOVE);
boolean isMoved = fileToMove.renameTo(new File(TARGET_FILE));
if (!isMoved) {
throw new FileSystemException(TARGET_FILE);
}
}
In this example, the file to be moved does exist, as well as the target directory.
在这个例子中,要移动的文件确实存在,目标目录也是如此。
Note that renameTo() only throws two types of exceptions:
注意,renameTo()只抛出两种类型的异常。
- SecurityException – if a security manager denies writing access to either the source or to the destination
- NullPointerException – in case the parameter target is null
If the target does not exist in a file system – no exception will be thrown – and you will have to check the returned success flag of the method.
如果目标在文件系统中不存在–将不会抛出异常–你将不得不检查方法返回的成功标志。
5. Using Guava
5.使用Guava
Next – let’s take a look at the Guava solution, which provides a convenient Files.move() method:
接下来–让我们看看Guava的解决方案,它提供了一个方便的Files.move()方法。
@Test
public void givenUsingGuava_whenMovingFile_thenCorrect()
throws IOException {
File fileToMove = new File(FILE_TO_MOVE);
File targetFile = new File(TARGET_FILE);
com.google.common.io.Files.move(fileToMove, targetFile);
}
Again, in this example, the file to be moved and the target directory need to exist.
同样,在这个例子中,要移动的文件和目标目录需要存在。
6. With Commons IO
6.有Commons IO
Finally, let’s take a look at a solution with Apache Commons IO – probably the simplest one:
最后,让我们来看看用Apache Commons IO的解决方案–可能是最简单的一个。
@Test
public void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
FileUtils.moveFile(FileUtils.getFile(FILE_TO_MOVE), FileUtils.getFile(TARGET_FILE));
}
This one line will, of course, allow both moving or renaming, depending on if the target directory is the same or not.
当然,这一行将同时允许移动或重命名,这取决于目标目录是否相同。
Alternatively – here’s a solution for moving specifically, also enabling us to automatically create the destination directory if it doesn’t already exist:
另外–这里有一个专门用于移动的解决方案,也使我们能够自动创建目标目录,如果它还不存在的话。
@Test
public void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
FileUtils.moveFileToDirectory(
FileUtils.getFile("src/test/resources/fileToMove.txt"),
FileUtils.getFile("src/main/resources/"), true);
}
6. Conclusion
6.结论
In this article, we looked at different solutions for moving a file in Java. We focused on renaming in these code snippets, but moving is, of course, the same, only the target directory needs to be different.
在这篇文章中,我们研究了在Java中移动文件的不同解决方案。在这些代码片断中,我们重点讨论了重命名,但移动当然也是一样的,只是目标目录需要不同。
The code for the examples is available over on GitHub.
例子的代码可在GitHub上找到。