想将程序用到的图片及其它文件跟class文件一起打包发布,按照我的理解,jar被加载后,包内所有的文件都应该可以以jar中的根目录为起始路径进行访问(类装载器将整个包读入后,既然可以按路径由Main-Class访问其它的class,自然也应该可以按照路径访问其它的非class文件),但事实似乎并非如此。
我的jar的目录结构如下所示:
/
com
images
META-INF
main.class

用于读取图片文件的代码如下:
public ImageIcon loadIconResource(String name) {
return new ImageIcon("images/ui/" + name);
}

但读取不出来。从网上查了n种方法,如:
return new ImageIcon(getClass().getResource("/images/ui/" + name));
return new ImageIcon(getClass().getResource("/images/ui/" + name));
return new ImageIcon(ClassLoader.getSystemResource("images/ui/" + name));
等等,均不能奏效。
郁闷中,谁能帮我解惑啊?
3x a lot!

解决方案 »

  1.   

    yes,以上几种方法在未打包时都可以工作,但打包后就不好使了,可是我看到的文章都说是在jar中读取资源文件的情况,整了一天没搞定,郁闷...
      

  2.   

    打包后 只有 new ImageIcon( getClass().getResource("/images/ui/"+name)) ) 这种方式.
    其实打印出来看就是 类似 C:/path/file.jar!/images/ui/logo.gif ,
     JAR 的URL 能够解析它 这种方式.你的写法不错,再仔细检查路径和文件名.
    把这个 getClass().getResource("/images/ui/" + name));  的结果打印出来.
      

  3.   

    return new ImageIcon(getClass().getResource("/images/ui/" + name));
    改成
    return new ImageIcon(getClass().getResource("images/ui/" + name));
      

  4.   

    非常感谢各位,尤其是humanity,终于知道原因了:
    jar资源名区分大小写!
    ^_^