2015-01-13 37 views
0

我在java中出现了一个奇怪的问题。我想创建一个可运行的jar: 这是我唯一的类:在可运行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())); 

} 

} 

正如你可以看到它只是输出,如果可以找到该文件或没有。 它在日食下正常工作(返回true)。我已经使用image 1.png创建了一个源文件夹资源。 (资源文件夹被添加到构建路径中的源代码)

只要我将项目导出到可运行jar并启动它,它就会返回false。 我不知道为什么。有人有一个想法? 在此先感谢

编辑:我跟着例如2创建资源文件夹:Eclipse exported Runnable JAR not showing images

回答

0

因为图像不是单独的文件,但在包装里面的.jar。

使用代码从流创建图像

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

我如何从InputStream到文件?换句话说,我怎么看文件是否存在? – Bosiwow

+1

流不为空 – StanislavL

+0

是的好吧,但我使用的是一个函数,期望PATH到图像。我想我不能通过输入流... – Bosiwow

0

尝试用它来获取图像

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

如果你想从你的.jar文件使用getClass().getResource()加载资源。这将返回具有正确路径的URL。

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

要访问罐子中的图像,请使用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) { } 
} 

还是你了解,请通过这个链接。

Eclipse exported Runnable JAR not showing images

+0

谢谢,我应该传递给“新文件”?为了使代码工作? – Bosiwow

0

两个简单的步骤:

1 - 添加的文件夹(其中图像),以构建路径;

2 - 使用此:

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