简体   繁体   English

在可运行的jar中导出图像不起作用

[英]Exporting image in runnable jar doesn't work

I'm having a weird problem in java. 我在Java中遇到一个奇怪的问题。 I want to create a runnable jar: This is my only class: 我想创建一个可运行的jar:这是我唯一的课程:

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()));

}

}

As you can see it just outputs if it can find the file or not. 如您所见,它只能输出是否可以找到该文件。 It works fine under eclipse (returns true). 在日食下工作正常 (返回true)。 i've created a source folder resources with the image 1.png. 我已经用图像1.png创建了一个源文件夹资源。 (resource folder is added to source in build path) (将资源文件夹添加到构建路径中的源中)

As soon as I export the project to a runnable jar and launch it, it returns false. 一旦将项目导出到可运行的jar并启动它,它就会返回false。 I don't know why. 我不知道为什么 Somebody has an idea? 有人有主意吗? Thanks in advance 提前致谢

edit: I followed example 2 to create the resources folder: Eclipse exported Runnable JAR not showing images 编辑:我按照示例2创建资源文件夹: Eclipse导出的Runnable JAR不显示图像

If you would like to load resources from your .jar file use getClass().getResource() . 如果您想从.jar文件中加载资源,请使用getClass().getResource() That returns a URL with correct path. 这将返回具有正确路径的URL。

Image icon = ImageIO.read(getClass().getResource("image´s path"));

To access images in a jar, use Class.getResource() . 要访问jar中的图像,请使用Class.getResource()

I typically do something like this: 我通常会这样做:

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) { }
}

Still you're understand, Kindly go through this link. 仍然您了解,请通过此链接。

Eclipse exported Runnable JAR not showing images Eclipse导出的Runnable JAR不显示图像

Because the image is not separate file but packed inside the .jar. 因为图像不是单独的文件,而是打包在.jar中。

Use the code to create the image from stream 使用代码从流中创建图像

InputStream is=Launcher.class.getResourceAsStream("/1.png");
Image img=ImageIO.read(is);

尝试使用它来获取图像

InputStream input = getClass().getResourceAsStream("/your image path in jar");

Two Simple steps: 两个简单步骤:

1 - Add the folder ( where the image is ) to Build Path; 1-将文件夹(图像所在的位置)添加到构建路径;

2 - Use this: 2-使用此:

InputStream url = this.getClass().getResourceAsStream("/load04.gif");
myImageView.setImage(new Image(url));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM