Why does getResource return null

2019-02-13 22:52发布

问题:

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

This is how my project looks like:

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

And how project folder in eclipse workspace looks like:

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

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

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");

回答1:

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"). 


回答2:

Try using / prefixing.

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



回答3:

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



回答4:

Use the following code, it should work.

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

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



回答5:

Either Approach will work. its just Filepath issue.

  • Your Jar Structure shows no "asset" Folder
    xxx.png file is directly in Jar File.

Try to remove "assets" from below line of code.

Thread.currentThread().getContextClassLoader().getResource("assets/xxx.png"); //returns null
  • Also, if you want to use "assets" folder in ur classpath, please ensure that your jar contains "assets" folder.