Alexander Pacha
Alexander Pacha

Reputation: 9710

Accessing resource in Java/Gradle Environment

My question is similar to this question but unfortunately, their answer didn't work for me. I have a gradle-based java project too with the following structure

.
├── myproject
│      ├── src
│      |    └── main
│      |         ├── java
│      |         └── resources
│      |               └── templates
│      |                      └── myresource.bmp
|      ├── build
|      |     ├── classes
|      |     └── resources
|      |          └── main
│      |               └── templates
│      |                      └── myresource.bmp

Since I want to run my code on Android and Windows, I'm accessing the resources with the following

ClassLoader classLoader = Thread.currentThread().getContextClassLoader()
res = classLoader.getResourceAsStream("templates/myresource.bmp");

This worked previously with Eclipse, because I just put my resources into the src-folder and it was copied to the target directory. But when migrating to Android Studio and Gradle, I moved the resources into the resources folder, where I thought they would belong and it's now no longer under the src/ path.

Now, whenever I execute that code, I only get null. To me it seems, that the path is somewhat incorrect. I tried the following paths:

but nothing seems to work.

Maybe I'm using the wrong classloader, but it actually looks ok. ClassLoader debugging paths

What would be the correct path, to load the resources? One more thing to mention: The project 'myproject' is in my case a library that loads the resources and it is called from another test-project, if that is somehow relevant.

Upvotes: 2

Views: 1235

Answers (1)

Tunaki
Tunaki

Reputation: 137064

The correct path would be /templates/myresource.bmp.

See this answer for more info: https://stackoverflow.com/a/3727998/1743880.

Upvotes: 1

Related Questions