简体   繁体   中英

java eclipse create executable jar

I used eclipse to create executable jar. It relies external other jars.
In Eclipse, It is simple that you just need to choose Extract required libraries into generated JAR .
You can create an executable jar. It can be executed any places where jre is installed.

But If I use command line to compile jar.
javac -classpath [external jars] *.java
jar cfm [a name].jar manifest *.class [external jars]

It can generate jar. But the jar can only be executed in the directory where it is produced. If I put it into another directory or machine, it complains NoClassDefFoundError .

So, my question is that how I can generate executable jar using command line as Eclipse.

A jar file cannot have its dependency jars inside. In case of Eclipse, it will unpack all the classes from the dependency jars and will bundle it into your single jar along with your class files. If not in the eclipse way, you need to

1) Create a manifest file which lists all the dependency jars

Manifest-Version: 1.0
Main-Class: Your Main class
Class-Path: dependency1.jar dependency2.jar dependency3.jar
 dependency4.jar dependency5.jar

2) Create your jar with your class files using the class path including all the dependency jars and using the above created mainfest file.

3) In this same folder where you created your jar, place all the dependency jars.

Now your folder will look like this,

yourjar.jar (With the manifest file you created above) dependency1.jar dependency2.jar dependency3.jar dependency4.jar dependency5.jar

4) Now if you want to share this, you need to share this folder and you can launch your jar from this folder. This is your executable folder and you can run it from anywhere.

Eclipse use Ant to package jar file, you can save the ant script that eclipse use to generate the jar checking the checkbox Save Ant File in the export window :

截图

so, you can generate the Ant Build.xml script and then execute it using ant directly from the command line without using eclipse anymore if you want.

My preferred method for creating an executable jar is to use a utility called one-jar. I have a blog post discussing how to use it in maven and ant: my one jar blog post

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