访问jar中的资源文件夹

时间:2015-08-19 11:50:20

标签: java json intellij-idea resources gson

我正在尝试在构建JAR后读取resource文件夹的内容。资源文件夹在IDE设置(IntelliJ)中标记为source

我尝试过以下方法:

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

我也尝试过:

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

这两种方法都会产生:

结果是:

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

文件结构:

src

-com.layers -> myClasses

-resources -> JSON

编辑:

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

结果:

java.lang.NullPointerException

1 个答案:

答案 0 :(得分:4)

通过getResourceAsStream()在Java中加载资源时,不理解绝对相对路径之间的区别是导致NullPointerException的错误的常见来源

假设以下结构和内容:

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

内容将在.jar中重新组织:

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

以下说明检索资源数据的作用和不起作用:

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()相对于与被调用的Class实例对应的包进行操作。