在这篇快速而简短的文章中,您将学习如何在 Java 中移动或重命名文件或目录。
您可以使用 Java NIO 的 Files.move() 方法来复制或重命名文件或目录。
import java.io.IOException;
import java.nio.file.*;
public class MoveFileExample {
public static void main(String[] args) {
Path sourceFilePath = Paths.get("./foo.txt");
Path targetFilePath = Paths.get(System.getProperty("user.home") + "/Desktop/foo.txt");
try {
Files.move(sourceFilePath, targetFilePath);
} catch (FileAlreadyExistsException ex) {
System.out.println("Target file already exists");
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}
如果目标文件已经存在,Files.move()
方法将抛出 FileAlreadyExistsException
。如果你想替换目标文件,那么你可以像这样使用 REPLACE_EXISTING
选项 -
Files.move(sourceFilePath, targetFilePath, StandardCopyOption.REPLACE_EXISTING);
如果要重命名文件,只需保持源文件和目标文件位置相同,只需更改文件名:
Path sourceFilePath = Paths.get("foo.txt");
Path targetFilePath = Paths.get("bar.txt");
// foo.txt will be renamed to bar.text
Files.move(sourceFilePath, targetFilePath);
您可以使用 Files.move()
方法移动或重命名空目录。如果目录不为空,则当目录可以移动而不移动该目录的内容时,则允许移动。
要移动目录及其内容,您需要为子目录和文件递归调用 move 。我们将在另一篇文章中讨论这一点。
以下是移动或重命名目录的示例:
import java.io.IOException;
import java.nio.file.*;
public class MoveDirectoryExample {
public static void main(String[] args) {
Path sourceFilePath = Paths.get("/Users/callicoder/Desktop/media");
Path targetFilePath = Paths.get("/Users/callicoder/Desktop/new-media");
try {
Files.move(sourceFilePath, targetFilePath);
} catch (FileAlreadyExistsException ex) {
System.out.println("Target file already exists");
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}