【发布时间】:2014-10-27 11:10:17
【问题描述】:
我想要一个静态 Path 属性来扫描子文件,这个 Path 引用了一个 zip 文件,我无法关闭它,因为它会被随机引用。在某些时候,我需要写入 zip 文件。问题是我不想关闭文件系统,因为 Path 属性需要打开以供将来阅读,如果我不关闭它,我就看不到写入的更改。如果我尝试创建另一个引用相同路径的文件系统,我会得到 FileSystemAlreadyExistsException。我可以在写入后关闭 fs 然后再次打开它,但此时有人可能会尝试读取路径。 有解决方法吗?为什么我不需要关闭默认文件系统来查看写入的文件,而我确实需要使用 zip 文件系统?
public static void copyTree(final Path source, final Path targetPath) throws IOException {
FileSystem fs = FileSystems.getFileSystem(targetPath.toUri());
Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Files.copy(dir, targetPath, StandardCopyOption.REPLACE_EXISTING);
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, targetPath, StandardCopyOption.REPLACE_EXISTING);
return super.visitFile(file, attrs);
}
});
//if I don't close the FileSystem here the changes won't appear.
fs.close();
}
【问题讨论】:
-
fs在您的示例中完全没用,除了close之外,它什么也不做,也没有被任何东西使用 - 基本上,您打开一个文件并再次关闭它而不明确阅读它。跨度>
标签: java concurrency java-7 nio