如何在 Java 中使用 FileUtils 移动文件?
java 8object oriented programmingprogramming更新于 2025/11/20 4:28:17
使用 File 类
java.io 包中的 File 类表示系统中的文件或目录(路径名)。此类提供了各种方法来对文件/目录执行各种操作。
此类提供了各种操作文件的方法。File 类的 rename() 方法接受一个表示目标文件的字符串,并将当前文件的抽象文件路径重命名为给定的路径。
此方法实际上将文件从源路径移动到目标路径。
示例
import java.io.File;
public class MovingFile {
public static void main(String args[]) {
//创建源文件对象
File source = new File("D:\source\sample.txt");
//创建目标文件对象
File dest = new File("E:\dest\sample.txt");
//重命名文件
boolean bool = source.renameTo(dest);
if(bool) {
System.out.println("File moved successfully ........");
}
else {
System.out.println("Unable to move the file ........");
}
}
}
输出
File moved successfully . . . . . . .
使用 Files 类
自 Java 7 开始,Files 类被引入,它包含操作文件、目录或其他类型文件的(静态)方法。
此类的 move 方法分别接受两个路径对象:source 和 destination(以及一个用于指定移动选项的变量参数),并将源路径表示的文件移动到目标路径。
示例
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MovingFile {
public static void main(String args[]) throws Exception {
//创建源 Path 对象
Path source = Paths.get("D:\source\sample.txt");
//创建目标 Path 对象
Path dest = Paths.get("E:\dest\sample.txt");
//复制文件
Files.move(source, dest);
System.out.println("File moved successfully ........");
}
}
输出
File moved successfully . . . . . . .

