使用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 教师闺蜜祝福语简短