Why getResource returns null

I am trying to access a file in my project. But the getResource method returns null.

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

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

And what the project folder looks like in the eclipse workspace:

enter image description here

Why? I want to access files in a folder with my resources?

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

enter image description here

solvable

First of all, I have many image files, so I want to organize them all in a folder. I put the resource folder in the src directory and finally was able to access the files.

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

enter image description here

+5
source share
5 answers

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

 Thread.currentThread().getContextClassLoader().getResource("/xxx.png"). 
+2
source

Try using the / prefix.

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

+1
source

Is there a reason you are using the class loader of the current class? Something like this.getClass().getClassLoader().getResource("/xxx.png") should be more reliable.

0
source

Use the following code, it should work.

YOUR_CLASS_HERE.class.getClass().getResource( "/xxx.png" );

eg. Signin.class.getClass().getResource( "/xxx.png" );

0
source

Any approach will work. its just a filepath problem.

  • Your jar structure does not show the asset folder
    The xxx.png file is located directly in the Jar file.

Try removing the “assets” from the bottom line of code.

 Thread.currentThread().getContextClassLoader().getResource("assets/xxx.png"); //returns null 
  • In addition, if you want to use the "assets" folder in the urpathpath, make sure that your jar contains the "assets" folder.
0
source

All Articles