如何读取位于嵌套 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:
我怎样才能得到那个图像?
附加信息:
- 我在 EAR 中尝试了一个分解的和非 epxloded 的 JAR。相同的结果。
- 资源路径似乎是正确的。以“/resources”作为前缀以返回 NULL 的方法结束。
- 我尝试使用 Class' 类加载器而不是线程上下文的类加载器。结果相同。
- 我设想自己浏览所有随附 JAR 的条目,但这似乎太过分而且困难:因为我有
JarInputStream
而没有 JarFile
,我将如何读取相应的数据到条目?
您的想法是正确的,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 实例不会告诉您太多信息。看内容,我觉得就是你要的图
我在尝试读取与 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:
我怎样才能得到那个图像?
附加信息:
- 我在 EAR 中尝试了一个分解的和非 epxloded 的 JAR。相同的结果。
- 资源路径似乎是正确的。以“/resources”作为前缀以返回 NULL 的方法结束。
- 我尝试使用 Class' 类加载器而不是线程上下文的类加载器。结果相同。
- 我设想自己浏览所有随附 JAR 的条目,但这似乎太过分而且困难:因为我有
JarInputStream
而没有JarFile
,我将如何读取相应的数据到条目?
您的想法是正确的,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 实例不会告诉您太多信息。看内容,我觉得就是你要的图