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/Lifepaths.txt
My code loads a file by calling Class::getResourceAsStream
to return a InputStream
.
public class Lifepaths {
public static void execute() {
System.out.println(Lifepaths.class.getClass().
getResourceAsStream("/initialization/Lifepaths.txt"));
}
private Lifepaths() {}
//This is temporary; will eventually be called from outside
public static void main(String[] args) {execute();}
}
The print out will always print null
, no matter what I use. I'm not sure why the above wouldn't work, so I've also tried:
"/src/initialization/Lifepaths.txt"
"initialization/Lifepaths.txt"
"Lifepaths.txt"
Neither of these work. I've read numerous questions so far on the topic, but none of them have been helpful - usually, they just say to load files using the root path, which I'm already doing. That, or just load the file from the current directory (just load filename
), which I've also tried. The file is being compiled into the JAR in the appropriate location with the appropriate name.
How do I solve this?
Lifepaths.class
. That being said, why doesgetClassLoader()
allow it to work? (Also, feel free to post an answer!)Lifepaths.getClass()
? There is no such static method defined in Object...getResource(String)
. BTW - I have always had problems getting either of those to work in astatic
context. The problem is basically that the class loader obtained is is the one intended for J2SE classes. You need to get access to the context class loader which is intended for the application itself.