2

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.

Sam YC
  • 10,725
  • 19
  • 102
  • 158

1 Answers1

3

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

tostao
  • 2,803
  • 4
  • 38
  • 61
Steves
  • 2,798
  • 21
  • 21
  • 4
    have tried that one, it will only work for the resource in classpath `src/main/resources`, doesn't work if resource is inside jar file. – Sam YC Aug 27 '20 at 07:51
  • @SamYC did you solve the problem? I have the same issue. My project has a dependency jar that contains files inside it and the dependency uses these files. As they are not included, my project doesn't work. – Jordan Silva Nov 06 '22 at 20:45
  • @JordanSilva yes, my problem is solved, it is mentioned in the "PS" part in my question. I removed the beginning slash in the path variable, then it works. – Sam YC Nov 07 '22 at 06:56