访问 .jar 文件中的图像文件时出现 NullPointerException
我几乎已经尝试了所有方法,但仍然遇到同样的问题。我有以下设置:我有一个 images.jar,其中包含一个名为“images”的文件夹,其中有多个图像文件。我将 images.jar 添加到 eclipse 中项目的 java 构建路径中,并且我一直在尝试使用以下代码来访问 jar 中的各个图像:
URL url = this.getClass().getResource("images/a.png");
ImageIcon icon = new ImageIcon (url);
不幸的是,URL 对象始终为 NULL。我不认为这与我放置 images.jar 文件的位置有任何关系,因为它被添加到 eclipse 中的类路径中。我也尝试过使用路径“/images/a.png”,但仍然存在同样的问题。任何建议都将非常受欢迎!谢谢。
I have pretty much tried everything but still have this same problem. I have the following setup: I have a images.jar containing a folder called 'images' in which there are multiple image files. I add images.jar to the java build path of the project in eclipse, and i've been trying to use the following code to access the individual images in the jar:
URL url = this.getClass().getResource("images/a.png");
ImageIcon icon = new ImageIcon (url);
Unfortunately, the URL object is always NULL. I don't think this has anything to do with where I put images.jar file as it is added to the classpath in eclipse. I have also tried using the path '/images/a.png', but still the same problem. Any suggestion would be extremely welcome! Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
如果没有
getClassLoader()
调用,您只能访问存储代码的 JAR 文件中的资源。Try this:
Without
getClassLoader()
invocation you are only able to access resources in JAR file where the code is stored.我无法重现您的问题,但我的理论是您从与您想象的不同的地方运行该类 - 图像和类位于不同的 jar 中,或者直接从类文件中读取该类。
I couldn't reproduce your problem, but my theory is that you are running the class from a different place than you think you are -- that the image and the class are in different jars, or the class is read directly from the class file.