java.nio.file.FileSystem可以为 zip 文件内的 zip 文件创建a 吗?
如果是这样,URI 是什么样的?
如果没有,我想我将不得不重新使用 ZipInputStream。
我正在尝试递归到下面的方法。当前的实现创建一个 URI“jar:jar:...”。我知道这是错误的(并且可能会让人想起电影角色)。应该是什么?
private static void traverseZip(Path zipFile ) {
// Example: URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
String sURI = "jar:" + zipFile.toUri().toString();
URI uri = URI.create(sURI);
Map<String, String> env = new HashMap<>();
try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
Iterable<Path> rootDirs = fs.getRootDirectories();
for (Path rootDir : rootDirs) {
traverseDirectory(rootDir ); // Recurses back into this method for ZIP files
}
} catch (IOException e) {
System.err.println(e);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用FileSystem.getPath返回一个Path适合与FileSystems.newFileSystem打开嵌套 ZIP/存档的另一个调用一起使用的文件。
例如,此代码打开一个 war 文件并读取内部 jar 文件的内容:
Path war = Path.of("webapps.war");
String pathInWar = "WEB-INF/lib/some.jar";
try (FileSystem fs = FileSystems.newFileSystem(war)) {
Path jar = fs.getPath(pathInWar);
try (FileSystem inner = FileSystems.newFileSystem(jar)) {
for (Path root : inner.getRootDirectories()) {
try (Stream<Path> stream = Files.find(root, Integer.MAX_VALUE, (p,a) -> true)) {
stream.forEach(System.out::println);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,您的代码可以传入 zipFile 而不更改为 URI:
try (FileSystem fs = FileSystems.newFileSystem(zipFile, env)) {
Run Code Online (Sandbox Code Playgroud)