Hi, I'm trying to use this.javaClass.getResource t...
# getting-started
j
Hi, I'm trying to use this.javaClass.getResource to read a resource from my resource folder but I always get null. Can anyone help (details in thread)?
I've added a folder 'src/test/resources' to my project and put a file dummy.pdf in it. I try to read this as a resource in my test class with
Copy code
val resource = this.javaClass.getResource("dummy.pdf")
but I only get null. When I get the current directory for the test with
.getResource(".")
I see that it is the package directory under
build/classes/kotlin/test
. So if I use
Copy code
val resource = this.javaClass.getResource("../../../../../../../../resources/test/dummy.pdf")
it works, but that seems impractical. Is it really supposed to work this way?
j
image.png
That's how I did it
And to use it:
a
this.javaClass.getResource("dummy.pdf")
fetches a path relative to the path of the compiled file in the assembled JAR. The assembled JAR is the contents of both
src/main/resources
and the compiled sources in
src/main/kotlin/
combined together, but each Kotlin file will be placed into a directory matching the package. A file
src/main/resources/foo/bar/my/application/dummy.pdf
will be copied into the JAR with a path of
/foo/bar/my/application/dummy.pdf
. A class with an FQN of
<http://foo.bar.my|foo.bar.my>.application.MyClass
will be compiled into the JAR with a path of
/foo/bar/my/application/MyClass.class
So
MyClass::class.javaClass.getResource("dummy.pdf")
will try and load a file relative to
/foo/bar/my/application/
, and that file doesn’t exist. Instead, you can load a file with an absolute path by adding a leading
/
Copy code
this.javaClass.getResource("/foo/bar/my/application/dummy.pdf")
or try and add enough `../`’s to navigate to the correct path. Or put
dummy.pdf
into a resources dir that matches the class package.
j
That works like a charm 🙂 . Thanks for your reply!
🦜 1
s
I now use https://github.com/goncalossilva/kotlinx-resources as this works also multiplatform.