想将程序用到的图片及其它文件跟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!
我的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!
其实打印出来看就是 类似 C:/path/file.jar!/images/ui/logo.gif ,
JAR 的URL 能够解析它 这种方式.你的写法不错,再仔细检查路径和文件名.
把这个 getClass().getResource("/images/ui/" + name)); 的结果打印出来.
改成
return new ImageIcon(getClass().getResource("images/ui/" + name));
jar资源名区分大小写!
^_^