java eclipse create executable jar

14,836

Solution 1

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.

Solution 2

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 :

screenshot

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.

Share:
14,836
chnet
Author by

chnet

improve myself.

Updated on June 04, 2022

Comments

  • chnet
    chnet almost 2 years

    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.