gpt4 book ai didi

java - zip 文件内的 zip 文件的文件系统

转载 作者:行者123 更新时间:2023-12-05 03:32:56 27 4
gpt4 key购买 nike

能否为压缩文件中的压缩文件创建 java.nio.file.FileSystem

如果是这样,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);
}
}

最佳答案

您可以使用 FileSystem.getPath 返回适合与另一个 FileSystems.newFileSystem 调用一起使用的 Path 来打开嵌套的 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);
}
}
}
}

另请注意,您的代码可以在不更改 URI 的情况下传入 zipFile:

try (FileSystem fs = FileSystems.newFileSystem(zipFile, env)) {

关于java - zip 文件内的 zip 文件的文件系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70398138/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com