英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论