访问 .jar 文件中的图像文件时出现 NullPointerException

发布于 2024-10-09 06:52:35 字数 410 浏览 0 评论 0原文

我几乎已经尝试了所有方法,但仍然遇到同样的问题。我有以下设置:我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

潦草背影 2024-10-16 06:52:35

试试这个:

URL url = this.getClass().getClassLoader().getResource("images/a.png");
ImageIcon icon = new ImageIcon(url);

如果没有 getClassLoader() 调用,您只能访问存储代码的 JAR 文件中的资源。

Try this:

URL url = this.getClass().getClassLoader().getResource("images/a.png");
ImageIcon icon = new ImageIcon(url);

Without getClassLoader() invocation you are only able to access resources in JAR file where the code is stored.

梦行七里 2024-10-16 06:52:35

我无法重现您的问题,但我的理论是您从与您想象的不同的地方运行该类 - 图像和类位于不同的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文