Creating a runnable jar file:
This quick tutorial gives a step by step process of creating
runnable jar files with the help of Ant. It is not the only way to do it, but it
is probably the easiest.
A runnable jar file allows a use to run Java classes without having to know
class names and type them in a command prompt, rather the user can just double
click on the jar file and the program will fire up. A runnable jar allows
Java classes to be loaded just like when a user clicks an exe file. The
easiest way to do this is to use Apache Ant. Ant is similar to a "make"
file in C++, but it is for Java.
- You need to start by installing Apache Ant and you can get the latest
release from http://ant.apache.org
- Ant works on an XML file named build.xml, so this must be created for your
project. You also will need a project folder and some subfolders
explained below.
- Start by creating a directory that will hold will project. You
need to create a subdirectory called "build" and another subdirectory called
"jar". Place all of your class
files for project in the build directory. We also need to create a file
called build.xml in the main project directory. Your build.xml file is where
you specify some tags for Ant to use, for our case of creating an runnable
jar, we will only need to create one tag. Below is an example of what this
tag should look like.
- <target name="jar">
<jar destfile="jar/MyProject.jar" basedir="build">
<manifest>
<attribute
name="Main-Class" value="MyProjectMain"/>
</manifest>
</jar>
</target>
- In this example we will get an output file
in the jar directory named "MyProject.jar". The key to creating the runnable
jar file is to specify a manifest class (Your manifest class is just the
class in your project that has main()). In the example above the manifest
class is "MyProjectMain".
- To run your Ant build file, open a command
prompt, navigate to your project folder and type:
- If you get an error saying "build.xml does
not exist" then you are either not located at the root of your project or
your build.xml file is not in the root of the project folder.
- At his point you should have a runnable jar
file to click on. If you click on it to open it and you get an error
saying that Java can't find your main class, review your build.xml and make
sure your paths are setup correctly. If the manifest is not specified
correctly Java won't know which class to run as your main class.
If you are having some problems or you want to
find out how make Ant do some more neat stuff life automatic compilation,
Javadoc, running, etc.. refer to this site
http://ant.apache.org/manual/index.html