Bootstrap FreeKB - Java - Create a JAR file that can be run as a Java Application from the command line
Java - Create a JAR file that can be run as a Java Application from the command line

Updated:   |  Java articles

In this tutorial, we will create a program using the Java programming language that can be run on the command line. The program will simply output "Hello World".

First, we will create a JAR file that will output Hello World, using Eclipse. In Eclipse, select  File New Java Project. Give your project a name, such as HelloWorld and select Finish.

 


Create a package

Expand your project, right-click on the src folder and select New > Package. Give your package a name, such as com.sample and select Finish.

 


Create Premain.java class

Right-click on the package, and select New Class. Give the class a name, such as Premain, and select Finish. In Premain.java, add the following markup.

AVOID TROUBLE

The premain class is used to avoid error Failed to load Premain-Class manifest attribute.

package com.sample;

import java.lang.instrument.Instrumentation;

public class Premain {
    public static void premain(String agentArgument, Instrumentation instrument) {
        System.out.println("Premain Java Agent Loaded");
    }
}

 


Create HelloWorld.java class

Right-click on the package, and select New Class. Give the class a name, such as HelloWorld, and select Finish.

 

In HelloWorld.java, add the following markup.

AVOID TROUBLE

public static void main is used to avoid error Main method not found in class or no main manifest attribute.

package com.sample;

public class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

 


Create MANIFEST.MF

Right-click on the src folder and select New > Folder and name the folder META-INF. Right-click on the META-INF folder and select New File and name the file MANIFEST.MF. Add the following to MANIFEST.MF.

Manifest-Version: 1.0
Premain-Class: com.sample.Premain
Main-Class: com.sample.HelloWorld

 


Create the JAR

Right-click on your project and select Export. Select JAR file and select Next. Select Browse and select a location on your local PC. Select Next and bullet Use existing manifest from workspace and select the MANIFEST.MF file. Select Finish.

 


View the JAR

Using the jar command, you can view the contents of the JAR file. In this example, the JAR will contain Premain.class and HelloWorld.class in the com/sample package.

META-INF/MAINFEST.MF
com/sample/HelloWorld.class
com/sample/Premain.class

 

And you should now be able to run your helloworld.jar file on the command line, and Hello World should be returned.

~]$ /path/to/java -jar /path/to/helloworld.jar
Hello World

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 39ac46 in the box below so that we can be sure you are a human.