This is a simple tutorial about making jar file and compiling the source code using command. As you may know that in java the class are packaged in jar file and provides as library. So it can be used in different module/project.
First we are going to make some suitable directory structure. Run the following commands
mkdir -p code4reference/com/jar touch code4reference/com/jar/TestJar.java touch MainJar.java
The above commands create following directory structure.
. ├── code4reference │ └── com │ └── jar │ └── TestJar.java └── MainJar.java
Now you can put some code in TestJar.java file. I have put something like this.
package code4reference.com.jar; public class TestJar { public void print(){ System.out.println("Hello World! from TestJar"); } }
As you may have noticed that the directory structure is resembling with the package name mentioned in the source file. Generally whenever you are making new java package you have to follow same directory structure. Otherwise some of the program would not be able to figure out your class file. Now it’s time to compile the source code. It is necessary to compile the java source files before creating the jar file. Run the following command to compile the source file.
javac -sourcepath . code4reference/com/jar/TestJar.java
In the above command -sourcepath is optional because the source file is present in the child directory. In-case source files are present in different directory then you need to provide the -sourcepath option. Javac command treat that value as the base directory for the source code.
Once the above command is executed a class file will get generated in the respective directory. In this case s TestJar.class file gets generated in code4reference/com/jar directory. Now it’s time to create jar file. Run the command given below.
jar -cf jartest.jar code4reference/
This command will create testjar.jar file in the current directory. You can refer the class(es) present in the jar file in java source file like the way it has been used in the source code below.
import code4reference.com.jar.TestJar; class MainJar{ public static void main(String args[]){ TestJar testjar = new TestJar(); testjar.print(); } }
Compile the source code using this command.
javac -cp testjar.jar MainJar.java
Once this command is executed you will see MainJar.class file in the current directory. Here -cp option has been used to give the referenced jar file name and location. Otherwise java compiler will throw class definition not found error. Now execute the command given below.
java -cp testjar.jar:. MainJar Hello World! from TestJar
Noticed that I have included “.” after test.jar: this gives a hint to the java application to look for the class in the jarfile as well as in the current directory. If this “.” is not provided then java throws this exception.
Error: Could not find or load main class MainJar
Please feel free to leave comments about post or website.Thanks