Java Tool Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 4.12, 2006

JAR File Format and 'jar' Tool

Part:   1  2  3  4   5 

Java Tool Tutorials

© 2006 Dr. Herong Yang

Latest updates:

  'javac' - The Java Compiler

  'java' - The Java Launcher

  'jdb' - The Java Debugger

  JAR File & 'jar' Tool

  Certificates and 'keytool'

  Installing J2SE 1.5.0

... Table of Contents

(Continued from previous part...)

Using JAR Files in Class Paths

One advantage of aggregating individual class files into a JAR file is that other Java tools recognize JAR files as collections of class files and allow you to use them in the class paths.

To test this, I created the following class, TempratureConvertorBean.java:

/**
 * TempratureConvertorBean.java
 * Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
 */
package herong;
public class TempratureConvertorBean {
  private double celsius = 0.0;
  private double fahrenheit = 32.0;
  public double getCelsius() {
    return celsius;
  }
  public void setCelsius(double c) {
    celsius = c;
    fahrenheit = 1.8*c + 32.0;
  }
  public double getFahrenheit() {
    return fahrenheit;
  }
  public void setFahrenheit(double f) {
    fahrenheit = f;
    celsius = (f-32.0)/1.8;
  }
  public String getInfo() {
    return new String("My TempraturConvertorBean - Version 1.00");
  }
}

I did the following to create a JAR file, herong.jar:

>mkdir cls

>javac -d cls TempratureConvertorBean.java

>jar cvf herong.jar -C cls herong
added manifest
adding: herong/(in = 0) (out= 0)(stored 0%)
adding: herong/TempratureConvertorBean.class(in = 798) (out= 458)...

>jar tf herong.jar
META-INF/
META-INF/MANIFEST.MF
herong/
herong/TempratureConvertorBean.class

I also created a testing class, F2C.java:

/**
 * F2C.java
 * Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
 */
import herong.TempratureConvertorBean;
public class F2C {
   public static void main(String[] arg) {
      TempratureConvertorBean b = new TempratureConvertorBean();
      double f = 0.0;
      if (arg.length>0) f = Double.parseDouble(arg[0]);
      b.setFahrenheit(f);
      double c = b.getCelsius();
      System.out.println("Fahrenheit = "+f);
      System.out.println("Celsius = "+c);
      System.out.println(b.getInfo());
   }
}

Here is what I did to test using JAR files in a class path:

>javac -classpath herong.jar F2C.java

>java -cp .;herong.jar F2C 70.0
Fahrenheit = 70.0
Celsius = 21.11111111111111
My TempraturConvertorBean - Version 1.00

This is nice. Right? I can take herong.jar to anywhere on any system. Just add it to "-classpath" for "javac" command, and "-cp" for "java" command.

(Continued on next part...)

Part:   1  2  3  4   5 

Dr. Herong Yang, updated in 2006
Java Tool Tutorials - Herong's Tutorial Notes - JAR File Format and 'jar' Tool