使用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 妈妈生日祝福语简短励志