问题描述
我试图将eclipse中的Java项目导出为可运行的jar,但是由于某些原因,可运行的jar无法正常工作.如果我双击可执行jar,它不会执行任何操作.我尝试了将所需的库提取并打包到生成的jar中.
I'm trying to export a java project in eclipse as a runnable jar, but for some reason the runnable jar doesn't work. If I double click the executable jar, it doesn't do anything. I tried both extract and package required libraries into generated jar.
因此,我还尝试导出一些更简单的项目,这些项目效果很好.最大的不同是我的真实项目中包含文件:图像和xml文件.
So I also tried to export some simpler projects, those worked fine. The biggest difference is my real project has files: images and xml files.
在代码中像这样引用它们:
In code reference them like this:
File file = new File("Recources/test.xml");
ImageIcon imageIcon = new ImageIcon("Recources/" + num + ".gif");
项目的结构如下:
但是在可执行jar中,它们看起来像这样:
But in the executable jar they look like this:
谢谢您的帮助.
我试过了'java -jar filename.jar',但是现在它说找不到我的资源文件夹,而在Eclipse中它仍然可以找到它.
I have tried the 'java -jar filename.jar', but now it says it can't find my resources folder, while in eclipse it can still find it.
推荐答案
JAR文件中的文件与存储在硬盘中的文件不一样.如果您将文件包含在JAR中,它们将被视为字节流.因此,您必须使用不同的方法来访问这些资源.
Files in a JAR-File aren't just like files stored in your hard-disc. If you include files in a JAR, they'll be seen as a Stream of Bytes. So you have to use different methods to access these resources.
//To read/access your XML-File
BufferedReader read = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/test.xml")));
//To read/access your gif-Files
ImageIcon icon = new ImageIcon(this.getClass().getResource("/"+num+".gif"));
"/"不是文件系统的根文件夹,而是JAR内部资源的根文件夹.
"/" is not the root-Folder of your file-system, but the root folder of the resources inside your JAR.
这篇关于使用eclipse导出的可运行jar无法正常工作,在eclipse中它仍然有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!