Hello, I want to package a folder containing some...
# community-support
a
Hello, I want to package a folder containing some json files together with my service module. The folder lives in the same directory as the module (I don't want to have it in the module because there is other services that use it too). I tried creating a source set in the build script for the module to include it as a resource for main as follows:
Copy code
sourceSets {
    main {
        resources {
            setSrcDirs(listOf("src/main/resources", "../external-resources/json-folder/"))
        }
    }
}
This solves my problem when I run
./gradlew build
locally, the files from that folder are all available in
/build/resources/
for the module. However, when I run the jar like this:
Copy code
java -jar build/libs/my-service-0.0.1.jar
I get a NullPointerException when trying to fetch one of the json files form resources. I get the resource like this from inside the module:
Copy code
javaClass.classLoader.getResource("./json-file.json")
Am I doing something wrong? Why is that file fetchable when building the jar and running unit tests that call the code to fetch that file but when running the jar I get the NullPointerException? Any help would be appreciated, thanks!
v
You can just do
srcDir("../external-resources/json-folder/")
to add that resource dir, instead of
setSrcDirs
and listing all, but that is not influencing your problem.
👍 1
Why it is not in the jar, probably depends on how you build that jar
Assuming you have some dependencies too, you somehow build this as bad-practice fat jar I assume, so the question is how you build it. But usually it should just work like what you showed. Can you maybe knit an MCVE?
a
managed to solve it by removing the "./" when getting the resource
thanks anyhow!
v
Oh, yeah, of course, could have seen that. 😄
If you do
getResource
on a class loader it is always absolute from the classpath root and must neither start with
.
nor
/
. If you do
getResource
on a class, it is always relative to that classes package, unless you start with
/
which makes it absolute.
a
interesting, I never knew that
👌 1