JarFile来自* .jar或输入流文件?

我有一个jar子或战争。

我是programmaticaly读取这个jar,当我在这个jar里面找到jar时,我想编程再次阅读它。

但是JarFile只提供了getInputStream,我无法将其传递给JarFile(文件文件)构造函数。

如何从jar读取jar?

编辑:我正在考虑从类加载器或类似的方式获取文件。

你可以在File System中创建jar文件

File tempFile=TempFile.createFile("newJar",".jar"); 

并将Stream写入其中。 之后你可以构造你的JarFile(tempFile)并处理它……

如果程序作为unsigned applet / JNLP运行,请忘记它,因为您无权在文件系统中创建文件…

更新:对不起,这可能为时已晚,我只是在评论中发现了你的最后一个问题。 所以我修改了这个例子来显示每个嵌套的条目被直接复制到OutputStream而不需要给外层jar充气。

在这种情况下, OutputStreamSystem.out但它可以是任何OutputStream (例如,到文件……)。


无需使用临时文件。 您可以使用JarInputStream而不是JarFile ,将InputStream从外部条目传递给构造函数,然后您可以读取jar的内容。

例如:

 JarFile jarFile = new JarFile(warFile); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = (JarEntry) entries.nextElement(); if (jarEntry.getName().endsWith(".jar")) { JarInputStream jarIS = new JarInputStream(jarFile .getInputStream(jarEntry)); // iterate the entries, copying the contents of each nested file // to the OutputStream JarEntry innerEntry = jarIS.getNextJarEntry(); OutputStream out = System.out; while (innerEntry != null) { copyStream(jarIS, out, innerEntry); innerEntry = jarIS.getNextJarEntry(); } } } ... /** * Read all the bytes for the current entry from the input to the output. */ private void copyStream(InputStream in, OutputStream out, JarEntry entry) throws IOException { byte[] buffer = new byte[1024 * 4]; long count = 0; int n = 0; long size = entry.getSize(); while (-1 != (n = in.read(buffer)) && count < size) { out.write(buffer, 0, n); count += n; } } 

通常,这是一个获取InputStream然后使用它的问题。 这允许您从大多数“在Web服务器上的jar中jar”问题和类似问题进行抽象。

显然,在这种情况下,它是JarFile.getInputStream()和JarInputStream()。

递归再次使用JarFile读取新的jar文件。 例如,

 import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; public class JarReader { public static void readJar(String jarName) throws IOException { String dir = new File(jarName).getParent(); JarFile jf = new JarFile(jarName); Enumeration en = jf.entries(); while(en.hasMoreElements()) { ZipEntry ze = (ZipEntry)en.nextElement(); if(ze.getName().endsWith(".jar")) { readJar(dir + System.getProperty("file.separator") + ze.getName()); } else { InputStream is = jf.getInputStream(ze); // ... read from input stream is.close(); System.out.println("Processed class: " + ze.getName()); } } } public static void main(String[] args) throws IOException { readJar(args[0]); } }