Wednesday, June 8, 2011

Java Jar in 11 easy-to-follow steps

$ mkdir -p FirstProject/source/com/anicehumble
$ cd FirstProject/source/
$ vim com/anicehumble/Person.java

Then enter this:
package com.anicehumble;

public class Person {
        public static void main(String[] args) {
                System.out.println("Hello World");
        }
}

$ mkdir ../classes
$ javac -d ../classes com/anicehumble/Person.java 

The javac -d will build your Person.java in a mirror path(package) of your source code's path. So if you put your source code under the path of com/anicehumble, the -d ../classes parameter tells the compiler to put your compiled code in com/anicehumble path too, and under the classes path.

$ cd ../classes/

To test if your program is running properly(note, should use dots, not forward-slash, nor back-slash):
$ java com.anicehumble.Person

To put your class file in a JAR, create a manifest file first, indicating which class should the java runtime will look for main method:

$ echo "Main-Class: com.anicehumble.Person" > manifest.txt

Then put the classes in the jar, along with the manifest file:
$ jar -cvmf manifest.txt FTW.jar com/anicehumble/Person.class

Alternatively, you can do this, jar recursively get all the files if you just specify directory:
$ jar -cvmf manifest.txt FTW.jar com

To run:
$ java -jar FTW.jar

To make sure that your jar file is indeed self-contained:
$ mv FTW.jar ~/Desktop/
$ cd ../..
mv FirstProject x_Project 

The last step(mv, Unix's rename) above is to make sure that there's no false positive ;-)
$ cd ~/Desktop/

To run:
java -jar FTW.jar

No comments:

Post a Comment