JAVA and JAR’s from the command line

This is a small little tutorial which will explain how to create your own little Java application which have dependencies which are in other JAR files

First create the following directory structure:

java_test
    |
    |__myapp
    |     |__src
    |     |   |__ch
    |     |       |__eitchnet
    |     |            |__java
    |     |                 |__Main.java
    |     |__META-INF
    |     |    |__MANIFEST.MF
    |     |__bin
    |
    |__mydep
    |     |__src
    |     |   |__ch
    |     |       |__eitchnet
    |     |            |__helloworld
    |     |                 |__HelloWorld.java
    |     |__bin
    |
    |__deploy
        |__lib

The MANIFEST.MF file has the following content:

	Main-Class: ch.eitchnet.java.Main
	Class-Path: mydep.jar

The Main.java file has the following content:

  package ch.eitchnet.java;

  import ch.eitchnet.helloworld.HelloWorld;

  public class Main {
      public static void main(String[] args) {
      HelloWorld hw = new HelloWorld();
      System.out.println("HelloWorld instances: " + hw.getInstancesCount());
    }
  }

The HelloWorld.java has the following content:

  package ch.eitchnet.helloworld;

  public class HelloWorld {
    private static int instances;

    public HelloWorld() {
      System.out.println("Created HelloWorld object");
      instances++;
    }

    public int getInstancesCount() {
      return instances;
    }

    protected void finalize() {
      instances--;
    }
  }

Change your directory to be in the root of our project

Compile the dependency first:

find mydep/src/ -name "*.java" | xargs javac -d mydep/bin/

Should you be using a windows system, then you have compile file by naming each one. See the java help file for more information

Create the jar:

jar cvf ./deploy/mydep.jar -C ./mydep/bin ./

Compile the app:

find myapp/src/ -name "*.java" | xargs javac -classpath ./deploy/*.jar -d myapp/bin/

Should you be using a windows system, then you have compile file by naming each one. See the java help file for more information

Create the jar:

jar cmvf ./myapp/META-INF/MANIFEST.MF ./deploy/myapp.jar -C ./myapp/bin ./

Run the app by specifying everything explicitly:

java -classpath ./deploy/myapp.jar:./deploy/mydep.jar ch.eitchnet.java.Main

Or by running directly allowing the MANIFEST.MF to do its magic:

java -jar ./deploy/myapp.jar

tutorial files

grretings eitch