使用 Java 从一个目录移动文件到另一个目录
我们可以使用 Files.move() API 从一个目录移动文件到另一个目录。以下是 move 方法的语法。
public static Path move(Path source,Path target,CopyOption... options) throws IOException
其中
source - 要移动的文件的源路径
target - 要移动的文件的目标路径
options - 选项,如 REPLACE_EXISTING、ATOMIC_MOVE
示例
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Tester {
public static void main(String[] args) {
//move file from D:/temp/test.txt to D:/temp1/test.txt
//make sure that temp1 folder exists
moveFile("D:/temp/test.txt", "D:/temp1/test.txt");
}
private static void moveFile(String src, String dest ) {
Path result = null;
try {
result = Files.move(Paths.get(src), Paths.get(dest));
} catch (IOException e) {
System.out.println("Exception while moving file: " + e.getMessage());
}
if(result != null) {
System.out.println("File moved successfully.");
}else{
System.out.println("File movement failed.");
}
}
}输出
File moved successfully.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP