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.
Advertisement
Answer
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