这就是我想要做的:
FileSystem fs1 = FileSystems.newFileSystem(Paths.get("f1.jar"), null);
FileSystem fs2 = FileSystems.newFileSystem(fs1.getPath("/f2.jar"), null);
但我在第二行收到 FileSystems.newFileSystem()
抛出的 java.nio.file.ProviderNotFoundException
。
我做错了什么?
谢谢!
最佳答案
你 have to首先提取嵌套的 jar。
编辑: oracle 论坛上的答案没有给出您必须先提取 jar 的明确原因。
这是报价from Rajendra Gutupalli 的博客(com.sun.nio.zipfs 的作者):
Let's assume that we have a Jar file nested inside a Zip. The following program prints the contents of the MANIFEST.MF file which is inside nested jarCompress1.jar file.
import java.io.BufferedInputStream; import java.nio.file.*; import java.util.HashMap; import java.util.Map; public class ReadEntry { public static void main(String... args) throws Exception { Path zipfile = Path.get("c:/zips/zip1.zip"); Map<String, String> env = new HashMap(); FileSystem manager = FileSystems.newFileSystem(zipfile, env,null); Path path = manager.getPath("/jarCompress1.jar/META-INF/MANIFEST.MF"); System.out.println("Reading input stream"); BufferedInputStream bis = new BufferedInputStream(path.newInputStream()); int ch = -1; while ((ch = bis.read()) != -1) { System.out.print((char) ch); } } }
还有一个one :
Important point to note here is, zip file path can expand to nested zips or jars in the file's path name. For example, /home/userA/zipfile.zip/DirA/dirB/jarFile.jar/META-INF/MANIFEST.MF accesses the jar file “jarFile.jar” inside Zip file “/home/userA/zipfile.zip”.
我无法重现声称的行为。下一段代码:
try (FileSystem fs1 = FileSystems.newFileSystem(Paths.get("f1.zip"), null)) {
Path path = fs1.getPath("/f2.zip/test.txt");
Files.lines(path).forEach(System.out::println);
}
给出异常(exception)
Exception in thread "main" java.nio.file.NoSuchFileException: f2.zip/test.txt
at com.sun.nio.zipfs.ZipFileSystem.newInputStream(ZipFileSystem.java:544)
at com.sun.nio.zipfs.ZipPath.newInputStream(ZipPath.java:645)
at com.sun.nio.zipfs.ZipFileSystemProvider.newInputStream(ZipFileSystemProvider.java:278)
at java.nio.file.Files.newInputStream(Files.java:152)
at java.nio.file.Files.newBufferedReader(Files.java:2781)
at java.nio.file.Files.lines(Files.java:3741)
at java.nio.file.Files.lines(Files.java:3782)
可能有人会确认这是一个错误或指出我的代码中的错误。
同时回到您最初的问题。您不能在 zip(jar) 中创建文件系统,因为没有可以从 ZipPath 创建 FileSystem
实例的 FileSystemProvider
(查看 newFileSystem
方法的源代码) .因此,您必须选择从外部 zip 中提取文件或编写您自己的 FileSystemProvider
实现。
关于java - 在另一个 jar 中获取一个 jar 的文件系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26219534/