I\'m loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:
/src/initialization/Life
The rules are as follows:
And try:
Lifepaths.class.getResourceAsStream("/initialization/Lifepaths.txt")
instead of
Lifepaths.class.getClass().getResourceAsStream("/initialization/Lifepaths.txt")
(not sure if it makes a difference, but the former will use the correct ClassLoader/ JAR, while I'm not sure with the latter)
There seems to be issue with the ClassLoader that you are using. Use the contextClassLoader to load class. This is irrespective of whether it is in a static/non-static method
Thread.currentThread().getContextClassLoader().getResourceAsStream
......
Roughly speaking:
getClass().getResource("/")
~= Thread.currentThread().getContextClassLoader().getResource(".")
Suppose your project structure is like the following:
├── src
│ ├── main
│ └── test
│ └── test
│ ├── java
│ │ └── com
│ │ └── github
│ │ └── xyz
│ │ └── proj
│ │ ├── MainTest.java
│ │ └── TestBase.java
│ └── resources
│ └── abcd.txt
└── target
└── test-classes
├── com
└── abcd.txt
// in MainClass.java
this.getClass.getResource("/") -> "~/proj_dir/target/test-classes/"
this.getClass.getResource(".") -> "~/proj_dir/target/test-classes/com/github/xyz/proj/"
Thread.currentThread().getContextClassLoader().getResources(".") -> "~/proj_dir/target/test-classes/"
Thread.currentThread().getContextClassLoader().getResources("/") -> null
I found myself in a similar issue. Since I am using maven I needed to update my pom.xml to include something like this:
...
</dependencies>
<build>
<resources>
<resource>
<directory>/src/main/resources</directory>
</resource>
<resource>
<directory>../src/main/resources</directory>
</resource>
</resources>
<pluginManagement>
...
Note the resource tag in there to specify where that folder is. If you have nested projects (like I do) then you might want to get resources from other areas instead of just in the module you are working in. This helps reduce keeping the same file in each repo if you are using similar config data