Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

java - Load image from jar and outside it in eclipse

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...