GraalVM native-image如何从Jar文件中读取资源文件

huangapple go评论84阅读模式
英文:

GraalVM native-image how to read resource file from Jar

问题

我有一个包含一些文本文件的 jar 文件,我正在尝试加载文件:

`InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);`

但是它不起作用,因为显示错误:

    [SUB] java.lang.NullPointerException
    [Thu Aug 27 12:07:48 SGT 2020][INFO] [SUB] 	at java.io.Reader.<init>(Reader.java:167)
    [Thu Aug 27 12:07:48 SGT 2020][INFO] [SUB] 	at hellofx.HelloFX.readFileAsStringFromJar(HelloFX.java:116)
    [Thu Aug 27 12:07:48 SGT 2020][INFO] [SUB] 	at hellofx.HelloFX.test(HelloFX.java:107)

如果我尝试将资源文件提取到类路径 `src/main/resources` 中,那么它就能正常工作。

我的问题是,在运行在 [GraalVM][1] 本地镜像中时,我们能够从 Jar 中读取资源文件吗?有很多第三方的 Java 库正在读取在同一个 Jar 中捆绑在一起的资源文件,我们如何解决这个问题?

附加信息更新:

的确是我的错误,混淆了 `class.getResource()` 和 `class.getClassLoader().getResource()`。一个需要在开头加上斜杠,另一个不允许加上。一旦我在 `path` 变量中去掉斜杠,它就能正常工作。

  [1]: https://www.graalvm.org/reference-manual/native-image/Resources/
英文:

I have a jar file which contain some text file inside, I am trying to load the file as:

InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);

It doesn't work as error showing :

[SUB] java.lang.NullPointerException
[Thu Aug 27 12:07:48 SGT 2020][INFO] [SUB] 	at java.io.Reader.<init>(Reader.java:167)
[Thu Aug 27 12:07:48 SGT 2020][INFO] [SUB] 	at hellofx.HelloFX.readFileAsStringFromJar(HelloFX.java:116)
[Thu Aug 27 12:07:48 SGT 2020][INFO] [SUB] 	at hellofx.HelloFX.test(HelloFX.java:107)

If I try to extract the resource file into classpath src/main/resources, then it is working fine.

My question is, could we read resource file from Jar (when running in GraalVM native-image)? There are plenty of third party Java libraries which are reading the resource files that are bundled together in the same Jar, how could we overcome this?

PS update:

it is indeed my mistake, confused with class.getResource() and class.getClassLoader().getResource(). One require slash in the beginning and another doesn't allow. Once I removed the slash in path variable, it is working fine.

答案1

得分: 3

你需要通过 -H:IncludeResources=path 来告诉本机图像要包含哪些资源。该值可以是正则表达式。

有关更多详细信息,请参阅文档:https://github.com/oracle/graal/blob/master/docs/reference-manual/native-image/Resources.md

英文:

You need to tell native image what resources to include via -H:IncludeResources=path. The value can be a regular expression.

See the documentation for more details: https://github.com/oracle/graal/blob/master/docs/reference-manual/native-image/Resources.md

huangapple
  • 本文由 发表于 2020年8月27日 12:20:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63609134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定