Runnable jar exported with eclipse isn't working, in eclipse it still works

你离开我真会死。 提交于 2020-01-25 20:55:08

问题


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.

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

The structure of the project looks like this:

But in the executable jar they look like this:

Thank you for your help.

Edit: 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.


回答1:


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

"/" is not the root-Folder of your file-system, but the root folder of the resources inside your JAR.




回答2:


The issue may be that Java is not the default program to run the jar.

Try right click -> Open with, and select the Java Runtime, and it should run successfully.

Make it the default program to enable double-click running.

Right click -> Properties -> Change -> C:\Program Files\Java\jre7\bin\javaw.exe

Inspired by stratwine's answer at https://stackoverflow.com/a/8511277




回答3:


So thank you all, but it seems like the problem wasn't the export only. There was an error I saw when I opened my program with cmd, I was using file name to open xml and images while I should have used inputStreams: https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html.



来源:https://stackoverflow.com/questions/33331397/runnable-jar-exported-with-eclipse-isnt-working-in-eclipse-it-still-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!