I'm not being able to read a JSON
file within resources
directory from my project's compiled jar.
But... first things first:
I've created a 'Gradle Groovy' Project within Intellij idea (v2017.3.4 Community Edition) with the following structure:
So, as you can see, I just have a Main.groovy
class and a resources
folder inside src/main
directory.
Inside resources
directory I've a single resource db/products.json
.
By going into File > Project Structure > Modules > Project Module > Sources
menu we can check that src/groovy
folder is marked as Sources
and resources
folder is marked as Resource Folder
, so I can assure that this folders are correctly set on classpath
:
On my Main class I've added following code line to load /db/products.json
resource:
By running the Project within Intellij idea I can check that the resource is loaded seamlessly:
Great! But...
Now the catch!
When I compile project with gradle
- through gradlew build
command - the jar lib ReadJSONResourceFile-1.0-SNAPSHOT
is generated inside build/libs
folder.
Looking at the jar's structure, we can check that db
resource folder is at the jar's root location:
But when I execute the jar through command:
groovy -cp build/libs/ReadJSONResourceFile-1.0-SNAPSHOT.jar -e "org.company.demo.Main.main()"
the resource is not successfully loaded. getResource()
just returns null
:
I've been trying to workaround this with other solutions provided here on Stack Overflow
but neither of them worked.
I'm missing something here... can you help?