InputStream.getResourceAsStream() giving null pointer exception

后端 未结 6 1441
广开言路
广开言路 2020-12-11 19:08

The line persistenceProperties.load(is); is throwing a nullpointerexception in the following method. How can I resolve this error?

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 19:46

    Short answer: Move persistence.properties to src/main/resources, have both Main.java and TestFunctions.java in src/main/java, and use

     getClass().getClassLoader().getResourceAsStream("persistence.properties");
    

    to load the properties file.

    Long answer with an explanation:

    As others have hinted at - in a Maven project structure, you (typically) have two directory trees: /src/main and /src/test. The general intent is that any "real" code, resources, etc should go in /src/main, and items that are test-only should go in /src/test. When compiled and run, items in the test tree generally have access to items in the main tree, since they're intended to test the stuff in main; items in the main tree, however, do not typically have access to items in the test tree, since it's generally a bad idea to have your "production" code depending on test stuff. So, since Main.java depends on TestFunctions.java, and TestFunctions.java depends on persistence.properties, if Main is in src/main then both TestFunctions and persistence.properties need to be as well.

提交回复
热议问题