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
What worked for me was to add the file under My Project/Java Resources/src
and then use
this.getClass().getClassLoader().getResourceAsStream("myfile.txt");
I didn't need to explicitly add this file to the path (adding it to /src
does that apparently)
So there are several ways to get a resource from a jar and each has slightly different syntax where the path needs to be specified differently.
The best explanation I have seen is this article from InfoWorld. I'll summarize here, but if you want to know more you should check out the article.
Methods
ClassLoader.getResourceAsStream()
.Format: "/"-separated names; no leading "/" (all names are absolute).
Example: this.getClass().getClassLoader().getResourceAsStream("some/pkg/resource.properties");
Class.getResourceAsStream()
Format: "/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's package
Example: this.getClass().getResourceAsStream("/some/pkg/resource.properties");
Updated Sep 2020: Changed article link. Original article was from Javaworld, it is now hosted on InfoWorld (and has many more ads)
You might want to try this to get the stream i.e first get the url and then open it as stream.
URL url = getClass().getResource("/initialization/Lifepaths.txt");
InputStream strm = url.openStream();
I once had a similar question: Reading txt file from jar fails but reading image works
Don't know if of help, but in my case I had my resource in the /src/ folder and was getting this error. I then moved the picture to the bin folder and it fixed the issue.
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
What you really need is a full absolute classPath for the file. So instead of guessing it, try to find out the ROOT and then move the file to a better location base one <.war> file structures...
URL test1 = getClass().getResource("/");
URL test2 = getClass().getClassLoader().getResource("/");
URL test3 = getClass().getClassLoader().getResource("../");
logger.info(test1.getPath());
logger.info(test2.getPath());
logger.info(test3.getPath());