[英]Load image from jar and outside it in eclipse
I have a structure like this in my java project in eclipse: 我在eclipse的java项目中有这样的结构:
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
. 当您尝试直接使用eclipse运行应用程序时会出现问题,因为(我想)res文件夹不在src文件夹中,您会得到一个
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: 另外,我发现我可以在eclipse中将
res
文件夹添加到class-path,以便可以通过以下方式加载它:
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. 在您的项目中创建一个
resources
文件夹,在eclipse中将其标记为源文件夹,将res
文件夹放置在resources
下,并确保您的非eclipse版本可以使用jar中resources
下的所有内容。 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. 您的问题是由以下事实引起的:非Eclipse构建会将
res
放入jar中,但是eclipse将res
的内容放入目标目录中。
You need to mark your res folder as a source folder (project properties > source > add folder). 您需要将res文件夹标记为源文件夹(项目属性>源>添加文件夹)。
Everything in this folder will be available on the classpath. 该文件夹中的所有内容都将在类路径上可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.