Menu

Sunday, July 3, 2011

Package a java application as a jar file using Eclipse IDE



In this below example, I have created a simple project with log4j library file and packaged it into an executable jar file.

1.       To create a simple project.
a.       Right click -> New -> Java Project -> Enter project name -> click Finish.



2.       Created a class called Main added the below code.

3.       In this project, I used log4j for logging purposes.
a.       Create a folder called lib and add the log4j.jar file. It is good practice to keep all the dependency jar files in the lib folder.
b.      Add this jar file into the build path. To do this
Right Click on the project -> Properties -> Java Build Path -> Add Jar
               
4.       To configure log4j, create a file called log4j.properties and add the below code. Add this log4j property file in the src folder.
log4j.rootLogger=DEBUG, file
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=C:/log/test.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} %5p - %m%n

5.       To package this project as a jar file.
a.       Right Click on the project -> Export -> Java -> Runnable Jar File ->
b.      Select the launch configuration.
c.       Enter name of the jar file in the Export destination
d.      Select “Package required libraries into generated Jar”
e.      Click finish.
f.        Now this application is packaged as a jar file.

6.       If you extract the jar file, it will be like this.
7.       To run a jar file, use below command.
java –jar jartest.jar