---
title: "jar打包不能显示图片问题"
author: "goodsense"
date: "2013-07-28T19:53:45Z"
tags: []
categories: ["编程语言"]
slug: "jar"
draft: false
lastmod: "2013-07-28T19:53:44Z"
id: 1914645
url: "https://goodsense.iteye.com/blog/1914645"
---

如果你的类有很多，并且包结构很复杂，那么你就不大可能把图片和类放在同一个层次上，而是应该把图片放到最外层，让所有的类通过绝对路径来访问该图片：

andy.jar |\_\_andycpp 

              |\__ GUITest.class

               |\__ images

                       |\__ Snap1.jpg

代码如下： 

java.net.URL imgURL = GUITest.class.getResource("/images/Snap1.jpg"); ImageIcon img1 = new ImageIcon(imgURL); 

大家看到和上述代码的区别了吗？区别非常细微，仅仅是在“images”的前面加了一个反斜杠"/"，这个反斜杠就表示根目录，没有反斜杠就表示相对路径。 补充：Class.getResource()、ClassLoader.getSystemResource()这些方法的搜索过程是比较复杂，值得好好研究研究 

java.net.URL imgURL = GUITest.class.getResource("images/Snap1.jpg"); ImageIcon img1 = new ImageIcon(imgURL); 

这里需要注意的是大小写问题！Jar文件内部对大小写是敏感的，因此，如果图片本身叫做snap1.jpg，你把路径写成images/Snap1.jpg，那么结果将找不到该图片。还要注意的是，每个类（注意，不是对象）都有一个 。