0

How can I get a file of a jar (inside a maven dependency) with getResourceAsStream method?

enter image description here

I tried following which returned null:

InputStream is = App.class.getResourceAsStream("jquery.js");
gartenkralle
  • 646
  • 1
  • 11
  • 21
  • 1
    try giving the full path starting from /META-INF – Prem Nov 02 '16 at 22:07
  • You'll definitely want to specify the fully-qualified path when retrieving class-path resources, but remember that "Maven Dependencies" is not actually a folder within your classpath. Since the resource is within a maven dependency jar file, you'll have to make sure that you're using the right classloader, and specifying the path appropriate within that context. – nbrooks Nov 02 '16 at 22:16

2 Answers2

1

There can be multiple reason for getResourceAsStream() returns null..

  • You should give the complete path inside the jar file starting with "/", otherwise it will retun null.
  • If your main class file and the jar file is not loaded by the same class loader, then it will return null. In that case, you need to use same class loader which is used to load the jar file. To test this, use the class file inside the jar file to get the class loader and use the getResourceAsStream method using that class loader.
  • Also, since the dependency is in maven, make sure that the dependency is runtime. Not compile time. The scope should not be "compile"
Prem
  • 329
  • 1
  • 11
0
InputStream is = App.class.getResourceAsStream("/META-INF/resources/webjars/jquery/2.1.4/jquery.js");

Worked fine! :)

gartenkralle
  • 646
  • 1
  • 11
  • 21