Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (10.2k points)

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

The code being used to load the file is:

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"

1 Answer

0 votes
by (46k points)
Lifepaths.class.getClass().getResourceAsStream(...) loads resources using system class loader, it obviously fails because it does not see your JARs Lifepaths.class.getResourceAsStream(...) loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARs

Related questions

0 votes
1 answer
asked Oct 29, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Oct 13, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
asked Aug 29, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...