Access resource folder within jar

故事扮演 提交于 2019-12-11 10:18:52

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/32094701/access-resource-folder-within-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!