How to create a runnable jar file from multiple java packages.
The below example has two packages mypkg1 & mypkg2 with the below directory structure
As you can see below I have 3 java files and two packages
1 2 3 4 5 6 7 8 9 |
# pwd /tmp/prog # du -a 4 ./mypkg1/One.java 4 ./mypkg1/Two.java 16 ./mypkg1 4 ./mypkg2/Res.java 8 ./mypkg2 |
Example java main method file.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package mypkg1; import mypkg2.Res; public class One { public static void main(String[] args) { Two two = new Two(); Res res = new Res(); System.out.println(two.Two(2, 2)); System.out.println(res.Res(4, 2)); } } |
Create a Manifest file
Note: mypkg1 contains the main and One is the class called
1 2 |
cat mypkg1/manifest.txt Main-Class: mypkg1.One |
Note: Make sure to leave two empty lines at the end
Lets first compile to java byte-code.
1 |
javac mypkg*/*.java |
Now we are ready to compile / create the jar file.
1 2 3 4 5 |
jar -cvfm mypkg1.jar mypkg1/mainfest.txt mypkg*/*.class added manifest adding: mypkg1/One.class(in = 510) (out= 354)(deflated 30%) adding: mypkg1/Two.class(in = 249) (out= 199)(deflated 20%) adding: mypkg2/Res.class(in = 249) (out= 199)(deflated 20%) |
To use the jar file just run
1 |
java -jar mypkg1.jar |
One last word about extra library files or any other static data.
By default java will search library and shared objects (so) files under the project folder/lib, make sure to include that in the jar file if needed.
alternatively use Apache Ant to auto build your project
Leave a Reply