How to use a jar file in java programs? (Compilation with jar files)

Posted by Joys of Programming on in Java

You may have often come across jar files which you have procured from some website or created yourselves. But if you want to make use of it or make use of certain classes defined in the java archive (jar), you must be able to compile with the jar file.

For further discussion, we will consider the jar file created here. tutorial.jar has two classes which are defined here. Let’s make use of these two classes in our test program Test.java.

/*Import the necessary packages*/
import tutorials.wmessage.WelcomeMessage;
import tutorials.sutils.StringUtils;

class Test {
 public static void main(String args[]) {

 /*Making use of the default welcome message*/
 WelcomeMessage wmessage1 = new WelcomeMessage();

 /*Making use of the default welcome message along with our own message*/
 WelcomeMessage wmessage2 = new WelcomeMessage("In Test.java");

 /*Making use of String Concatenation method defined in tutorials.sutils package*/
 String message = StringUtils.stringConcatenate(wmessage1.welcomeMessageString(),wmessage2.welcomeMessageString());

 /*Printing the combined Message*/
 System.out.println(message);
 }
}

As you can see, we are making use of the two packages tutorials.sutils and tutorials.wmessage. Now comes the important part.

How to make use of the tutorial.jar file.

javac has an option ” -cp” which corresponds to specifying the classpath. So to make use of tutorial.jar, we must specify the location of tutorial.jar. For our current scenario, let’s assume it is in the same directory. Then to make use of it, we must specify the current directory as the classpath or the complete filename.


$ javac Test.java -cp tutorials.jar

You are able to successfully compile the program Test.java. But the next challenge is to run the program. Since the main() function is in Test.java, we must specify this while archiving this file with tutorials.jar

The command jar has an option e (since JDK 6) to specify the main class or the starting point of a package

$ jar ufe tutorials.jar Test Test.class


The option u is to update the jar file.

Now to execute the program, we can use the -jar option of java

$ java -jar tutorials.jar
Welcome to the world of Java programming
Welcome to the world of Java programming
In Test.java



We have a major challenge before us. How to integrate our programs when we have multiple jar files? Thanks to tools like ant, maven, we can easily perform such tasks.

Tags: , , , , , , ,

Comments:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2009-2012 Joys of Programming All rights reserved.
Desk Mess Mirrored v1.8.1 theme from BuyNowShop.com.