Unable to import xml file from resource stream
Solution 1:
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
Solution 2:
The rules are as follows:
- check the location of the file you want to load inside the JAR (and thus also make sure it actually added to the JAR)
- use either an absolute path: path starts at the root of the JAR
- use an relative path: path starts at the package directory of the class you're calling getResource/ getResoucreAsStream
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)
Solution 3:
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)