Files.delete未正确删除文件夹



在springboot项目中,文件合并后,需要删除它们。合并方法的主要代码是:

// chunkFolder indicates the file storage folder path
Files.list(Paths.get(chunkFolder))
.filter(path -> path.getFileName().toString().contains(HYPHEN))
.sorted((p1, p2) -> {
String fileName1 = p1.getFileName().toString();
String fileName2 = p2.getFileName().toString();
int index1 = fileName1.indexOf(HYPHEN);
int index2 = fileName2.indexOf(HYPHEN);
return Integer.valueOf(fileName1.substring(0, index1)).compareTo(Integer.valueOf(fileName2.substring(0, index2)));
})
.forEach(path -> {
try {
Files.write(Paths.get(target), Files.readAllBytes(path), StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
);

删除方法为:

public void deleteDirectory(Path targetPath) throws IOException {
Files.walk(targetPath).sorted(Comparator.reverseOrder()).forEach(path -> {
try {
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
});
}

在windows环境测试中,删除合并后的存储路径。但是,结果显示该文件夹仍然存在,但无法访问。如果您停止springboot项目,文件夹就会消失。

当您没有正确关闭所有目录流时,Windows会出现此问题。您必须关闭代码中扫描的所有目录流。您展示的两个例子可以通过try-with-resources修复:

try(Stream<Path> stream = Files.list( ... )) {
... your code
stream.xyz(...);
}

加上CCD_ 2中的CCD_。检查所有代码中的其他类似调用。

当这种情况发生时,在Windows资源管理器中查看时,目录处于一种奇怪的状态——可见但不可访问。关闭虚拟机将正确清除,文件夹将从资源管理器中消失。

最新更新