getResourceAsStream returns null

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?

22 Answers
22

Leave a Comment