Load image from jar and outside it in eclipse

2020-02-07 05:25发布

问题:

I have a structure like this in my java project in eclipse:

  • src/com/myprogram/.../foo.java
  • res/icon.png
  • .project
  • ...

I Know that you can load an image from inside a jar with

ImageIO.read(getClass().getResource("/res/icon.png"));

The problem come when you try to run the application with eclipse directly as (I guess) res folder isn't inside src folder, you get a null URL. And I want to have separate folders for source code and for resources.

Also, what I have found is that I can add res folder to class-path in eclipse so I can load it with:

URL url = getClass().getResource("/res/icon.png");
if (url == null)
    url = getClass().getResource("/icon.png");
ImageIO.read(url);

But this add code that is only needed when you develop, and I don't like do things like this (code should be as clean and final as possible).

Can something done so the icon is read with both methods with the same code?

回答1:

Create a resources folder in your project, mark it as a source folder in eclipse, put the res folder under resources, and make sure your non-eclipse build uts everything that is under resources in the jar. Then load the icon using

getClass().getResource("/res/icon.png")

Your problem is caused by the fact that you non-eclipse build puts res in the jar, but eclipse puts the content of res in the target directory.



回答2:

You need to mark your res folder as a source folder (project properties > source > add folder).

Everything in this folder will be available on the classpath.