How to run Java program from jar file in command line

So you got a JAR file which contains your favorite Java game and you are wondering How to run Java program from JAR  file? Or you may be simply trying your hand after running Java program from command prompt and Eclipse IDE. Anyway its good to know How to execute Java program from JAR file, as JAR file is most popular way of shipping Java programs. JAR file usually contains all source and resource in form of class files, images, sound files etc. In order to run Java program from JAR file, it must be an executable JAR file i.e. it manifest file inside META-INF folder must contain a Main-class entry like Main-Class: Hello, which specify name of Java class which contains standard main method in Java. Without Main-class entry you can not run a JAR file in Java and if you try to run such jar file using jar command you will get error "Failed to load Main-Class manifest attribute from HelloWorld.jar". If you are not very much familiar with JAR file and don't know How to create an executable JAR, See this step by step tutorial on How to create executable JAR in Java. In this tutorial we will only focusing on running Java program from an executable JAR file.

Running Java program from JAR file in Java

How to run Java program from JAR file in command promptSuppose we have hello.jar which contains class which has main method as entry point. When we run this JAR file using JAR command, JVM will call this main method which is specified in its manifest file as shown below :

Manifest-version: 1.0
Main-Class: Hello

By the way don't forget to set PATH and  Classpath in Java before running Java program. If classpath is specified in manifest file than that will be used by JVM and it will ignore CLASSPATH environment variable, If you are not familiar with these details then see How classpath works in Java, must read for any beginner in Java. Once you are sure that Java is installed in your machine, path and classpath are proper, just execute following command and it will run your Java program from JAR file itself :

java -jar Hello.jar

If you face any issue related to Java, classpath and path while running your Java program from JAR file, please post here.

Other Java programming tutorial you may find useful

1 comment:

  1. Make a batch file like this ...

    @echo off
    c:\Windows\System32\java.exe -jar %1

    (or whatever path contains your current updated java.exe)

    name it JavaRun.bat
    and put it of course in System32
    then just type at the command line "JavaRun (name of your jar file)" and it executes
    That's it