且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Java NIO将文件从一个目录移动到另一个目录

更新时间:2022-11-28 19:16:43

Files.move 不等同于 mv 命令。它不会检测到目的地是目录并将文件移动到那里。

Files.move is not equivalent to the mv command. It won't detect that the destination is a directory and move files into there.

您必须逐个文件构建完整的目标路径。如果要将 /src/a.txt 复制到 / dest / 2014 / ,目标路径需要

You have to construct the full destination path, file by file. If you want to copy /src/a.txt to /dest/2014/, the destination path needs to be /dest/2014/a.txt.

您可能想要这样做:

File srcFile = new File("/src/a.txt");
File destDir = new File("/dest/2014");
Path src = srcFile.toPath();
Path dest = new File(destDir, srcFile.getName()).toPath(); // "/dest/2014/a.txt"