I have a Jar (we'll call it a.jar
) with a resource in it at path foo/bar.txt
and a function as follows:
object FooBarLoader {
fun loadFooBarText() = javaClass.getResourceAsStream("foo//bar.txt")
?.bufferedReader()
?.readLines()
?.joinToString("\n")
}
When I test the function in a unit test (JUnit 4, running with Gradle 6), it loads the text from the resource file despite the obvious typo (the //
in the middle of the resource path).
I also have a CLI application (in b.jar
) that has a dependency on a.jar
. When the CLI application calls loadFooBarText()
, it got a null result due to the resource not being found. This was fixed by fixing the typo (//
-> /
) in the function in a.jar
. No other changes were needed to fix it.
So, my question is why did the wrong path work in one situation (unit tests of a.jar
) and not the other (call from b.jar
)?
How do you run the unit test with a.jar
? Just run it in your IDE or use command java -jar a.jar
?
If you ran it just in IDE,I think difference is the search path
between local files and zip
files .
Your first application searches the file in your target directory
and the second application searches it in the jar
which is a compressed file.
When searching files in local path, command will be changed to right one by system.
The two commands below are the same in both Windows/Linux.
cd work//abc/ddd
cd work/abc/ddd
But when searching files in a jar
file which is actually compressed zip
file, path should be a restrict written or else the program will find nothing.