如何读取位于嵌套 JAR 中的图像资源的字节?

How to read the bytes of an image resource located inside a nested JAR?

我在尝试读取与 JAR 资源捆绑在一起的 PNG 图像的字节时遇到困难。该文件位于 src/main/resources 目录中。

到目前为止,这是我的代码:

byte[] bytes = {};
final InputStream defaultImageStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("/defaultLogo.png");
new DataInputStream(defaultImageStream).readFully(bytes);

代码在 Wildfly 12 服务器上执行,位于作为 EJB 包含在 EAR 中的 JAR 中。

似乎不​​是检索我要求的资源,而是 getResourceAsStream returns 封闭的 jar:

我怎样才能得到那个图像?

附加信息:

您的想法是正确的,JarInputStream 将为您服务。

您的代码应如下所示--

 try {
        JarInputStream jarIS = new JarInputStream(new FileInputStream(
                "jarfilePath"));

        JarEntry entry = null;
        while ((entry = jarIS.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (name.endsWith("defaultLogo.png")) {
                System.out.println( "You got the PNG File"+entry.getAttributes().toString() );
                //Now handle your stream as per your requirement.

            }
        }
    } catch (Exception e) {
    }

我认为您的代码按预期工作。查看 DataInputStream 实例不会告诉您太多信息。看内容,我觉得就是你要的图