我在 java 中遇到了一个奇怪的问题。我想创建一个可运行的 jar: 这是我唯一的类(class):
public class Launcher {
public Launcher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String path = Launcher.class.getResource("/1.png").getFile();
File f = new File(path);
JOptionPane.showMessageDialog(null,Boolean.toString(f.exists()));
}
}
如您所见,它仅输出是否可以找到该文件。 在eclipse下工作正常(返回true)。我已经使用图像 1.png 创建了源文件夹资源。 (资源文件夹添加到构建路径中的源中)
一旦我将项目导出到可运行的 jar 并启动它,它就会返回 false。 我不知道为什么。有人有主意吗? 提前致谢
编辑:我按照示例 2 创建了资源文件夹:Eclipse exported Runnable JAR not showing images
最佳答案
如果您想从 .jar 文件加载资源,请使用 getClass().getResource()
。这会返回一个具有正确路径的 URL。
Image icon = ImageIO.read(getClass().getResource("image´s path"));
要访问 jar 中的图像,请使用 Class.getResource()
。
我通常会做这样的事情:
InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
throw new RuntimeException("Icon.png not found.");
}
try {
return ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
stream.close();
} catch(IOException e) { }
}
您还是明白了,请浏览此链接。
关于java - 导出可运行 jar 中的图像不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27921230/