How to build a distributable jar with Ant for a ja

2019-02-19 08:54发布

问题:

I have a Java project in Eclipse with class MainClass having main method in package :

com.nik.mypackage. 

The project also references two external libraries, which I copied in the lib folder in Eclipse and then added to build path using ADD JAR function. The libraries being one.jar and two.jar

This library is in lib folder in eclipse and added to the build path.

I want to create a executable JAR of the application using ant script. So that user can access my application using command:

c:>java -jar MyProject-20111126.jar

I know about the Eclipse plugin which directly exports a java application as runnable JAR. But I want to learn ant and the build process so manually want to create the build.xm.

回答1:

You have two options from your build.xml. You can either unjar the library jars and then bundle their contents with the code compiled for your application. Or, you can put the library jars on the filesystem and supply a ClassPath entry in the manifest file of the MyProject-2011126.jar file.

If you set the classpath in the manifest remember that the path you supply is relative to the MyProject-2011126.jar.



回答2:

one alternative:

Instead of having only a jar, you build mutiple jars (your jar + libs) +batch file.

So, your built package can be like this structure:

  -/package/bin/app.bat
   /package/lib/my.jar
   /package/lib/one.jar
   /package/lib/two.jar

In app.bat you just have the same as your code

java -jar MyProject-20111126.jar

PS: if you want to start learning built tools, ANT may be a bit tool old. I suggest http://maven.apache.org/



回答3:

Please try one-jar. It helps to redistribute everything packaged as single jar and comes with ant-task . See Easiest way to merge a release into one JAR file.



标签: java ant build jar