我正在使用NIO库,但是在尝试将文件从一个目录移动到另一个目录时遇到一个奇怪的错误。
String yearNow = new SimpleDateFormat("yyyy").format(
Calendar.getInstance().getTime());
try {
DirectoryStream<Path> curYearStream =
Files.newDirectoryStream(sourceDir, "{" + yearNow + "*}");
//Glob for current year
Path newDir = Paths.get(sourceDir + "//" + yearNow);
if (!Files.exists(newDir) || !Files.isDirectory(newDir)) {
Files.createDirectory(newDir);
//create 2014 directory if it doesn't exist
}
}
循环访问以“ 2014”开头的元素,并将其移动到新目录(newDir,也称为2014)中
for (Path p : curYearStream) {
System.out.println(p); //it prints out exactly the files that I need to move
Files.move(p, newDir); //java.nio.file.FileAlreadyExistsException
}
我收到java.nio.file.FileAlreadyExistsException,因为我的文件夹(2014)已经存在。我实际上想要做的是将所有以“ 2014”开头的文件移动到2014目录中。
Files.move
不等同于该mv
命令。它不会检测到目的地是目录,也不会将文件移动到该目录。
您必须逐文件构造完整的目标路径。如果要复制/src/a.txt
到/dest/2014/
,则目标路径必须为/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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句