从jar中加载映像并在eclipse中加载映像 [英] Load image from jar and outside it in eclipse
问题描述
- src / com / myprogram /.../ foo我的Eclipse项目中有一个这样的结构。 java
- res / icon.png
- .project
- ...
我知道你可以从一个jar加载一个图像
ImageIO.read(的getClass()的getResource( / RES /的icon.png)。);
当您尝试使用eclipse直接运行应用程序时,问题出现(我猜)res文件夹isn在src文件夹里面,你得到一个 null
URL
。而且我想为源代码和资源提供单独的文件夹。
另外,我发现我可以添加 res
文件夹到eclipse中的class-path,所以我可以加载它:
URL url = getClass()。getResource ( /res/icon.png);
if(url == null)
url = getClass()。getResource(/ icon.png);
ImageIO.read(url);
但是这个添加代码只有在开发时才需要,而且我不喜欢这样做
可以完成任何事情,以便使用相同代码的两种方法读取图标?
在项目中创建一个资源
文件夹,将其标记为eclipse中的源文件夹 res
文件夹在资源
下,并确保您的非eclipse构建了资源
在jar中。然后使用
getClass()加载图标getResource(/ res / icon.png)
您的问题是由于您的非eclipse构建将 res
在jar中,但eclipse将 res
的内容放在目标目录中。
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?
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.
这篇关于从jar中加载映像并在eclipse中加载映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!