JarFile是从*.jar或输入流文件?

ble*_*esd 3 java

我有一个罐子或战争.

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

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

如何从jar读取jar?

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

Ric*_*ler 6

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

在这种情况下,OutputStreamIS System.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;
    }
}
Run Code Online (Sandbox Code Playgroud)