使用Java将文件从一个目录移动到另一个目录
我们可以使用Files.move()API将文件从一个目录移动到另一个目录。以下是move方法的语法。
public static Path move(Path source,Path target,CopyOption... options) throws IOException
哪里
source-要移动的文件的源路径
目标-文件的目标路径移动
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) {
//将文件从D:/temp/test.txt移至D:/temp1/test.txt-
//确保temp1文件夹存在
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("文件已成功移动。");
}else{
System.out.println("文件移动失败。");
}
}
}输出结果
文件已成功移动。
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语