Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access resource folder within jar

I am trying to read the contents of a resource folder once my JAR is built. The resource folder is marked as a source in the IDE settings (IntelliJ).

I have tried the following methods:

  InputStream input = getClass().getResourceAsStream("../objectLocation.json");
  JsonReader jsonReader = new JsonReader(new InputStreamReader(input));

I have also tried:

  JsonReader jsonReader = new JsonReader(new FileReader("../resources/objectLocation.json"));

Both of these methods results in :

Which results in:

java.io.FileNotFoundException: com/layers/resources/objectLocation.json (No such file or directory)

File structure:

src

-com.layers -> myClasses

-resources -> JSON

EDIT:

  InputStream input = getClass().getResourceAsStream("objectLocation.json");
  JsonReader jsonReader = new JsonReader(new InputStreamReader(input));

Results in a:

java.lang.NullPointerException
like image 259
Colin747 Avatar asked Jul 09 '26 17:07

Colin747


1 Answers

Not understanding the difference between absolute and relative paths when loading resources in Java via getResourceAsStream() is a common source of errors leading to NullPointerException.

Assuming the following structure and content:

My Project
  |-src
    |-main
      |-java
      | |-SomePackage
      |   |-SomeClass.java
      |-resources
        |-Root.txt
        |-SomePackage
          |-MyData.txt
          |-SomePackage2
            |-MySubData.txt

Content will be re-organized as following in the .jar:

|-Root.txt
  |-SomePackage
    |-SomeClass.java
    |-MyData.txt
    |-SomePackage2
      |-MySubData.txt

The following indicates what works and what does not work to retrieve resource data:

InputStream IS;
IS = SomeClass.class.getResourceAsStream("Root.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("/Root.txt"); // OK

IS = SomeClass.class.getResourceAsStream("/MyData.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("MyData.txt"); // OK

IS = SomeClass.class.getResourceAsStream("/SomePackage/MyData.txt"); // OK

IS = SomeClass.class.getResourceAsStream("SomePackage/MyData.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("MySubData.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("SomePackage/SomePackage2/MySubData.txt"); // OK

IS = SomeClass.class.getResourceAsStream("/SomePackage/SomePackage2/MySubData.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("/SomePackage2/MySubData.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("SomePackage2/MySubData.txt"); // OK

getResourceAsStream() operates relative to the package corresponding to the called Class instance.

like image 188
Keith Avatar answered Jul 12 '26 08:07

Keith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!