Monday, 12 September 2016

How to create jar file from Java Project and Run using Command Prompt?

I am using eclipse.

Create Java Project and add few classes to it.
Now a jar file can be exported as JAR or Runnable JAR.

The Difference between JAR and Runnable JAR is that the later has Entry point( Main Class) defined in it so that if we run the jar from command Prompt  it gets executed.

Steps ->
1.Right click on project and select Export 
2.Select Runnable JAR option and Click Next
3.Now select Entry Point in Launch Application Option. (Eg. Main Method)
4.Save .

Now your JAR file is created.
Each JAR file has  META-INF/MANIFEST.MF file which has default settings.
But when we create jar File as Runnable JAR entry point gets created in MANIFEST.MF file
as Main-Class:PackageName.ClassName  
Eg. Main-Class:com.tush.pat.TestClass

Whenever entry point is not mentioned in class add above line to it and then run .

Note**-
Whenever we create jar file simply as JAR we often miss to mention entry point in jar .
Hence jar file first has to be made runnable and then run.

To avoid it we can directly create runnable jar.

How to run ?
1.Open cmd and cd to jar file location.
2. java -jar abc.jar    
 where abc.jar is our jar file

It will execute the jar file.



No comments:

Post a Comment