Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getResource return null

I'm trying to access a file in my project. But getResource method returns null.

This is how my project looks like: enter image description here

Thread.currentThread().getContextClassLoader().getResource("assets/xxx.png"); //returns null

And how project folder in eclipse workspace looks like:

enter image description here

Why? I want to access files in my assets folder?

Edit I created a jar file and this is content of the jar:

enter image description here

Solved

First of all, I've a lot of image files so I want to organize all them in a folder. I put the assets folder in src directory and finally I was able to access the files.

this.getClass().getClassLoader().getResource("assets/xxx.png");

enter image description here

like image 391
amone Avatar asked Sep 28 '22 03:09

amone


3 Answers

There are lot of ways to add a resource to the jar file, you can put it in src, add as a resource if you use maven, ant etc... If you able to bundle whole directory then you should be able to use your original piece of code. With the current structure you can use following piece of code.

Thread.currentThread().getContextClassLoader().getResource("/xxx.png"). 
like image 169
Eranda Avatar answered Oct 13 '22 00:10

Eranda


Try using / prefixing.

Thread.currentThread().getContextClassLoader().getResourceAsStream("/xxx.png")

like image 32
Dilip Kumar Avatar answered Oct 12 '22 23:10

Dilip Kumar


For someone struggling as me. For Maven just run mvn clean install. After that Thread.currentThread().getContextClassLoader().getResource() should work.

like image 38
LexSav Avatar answered Oct 12 '22 23:10

LexSav