简体   繁体   中英

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

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.

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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