Share on Google+Share on Google+

How to Create Jar File using Java

In this section,you will learn how to create our own jar file.

How to Create Jar File using Java Programming Language

A Jar file combines several classes into a single archive file. Basically,library classes are stored in the jar file.  In this section, we are going to create our own jar file. For this, we have created a method createJarArchive(File jarFile, File[] listFiles)where we have used the classes JarOutputStream class which write the contents of a JAR file to the output stream and Manifest class which specify the meta-information about the JAR file and its entries. Then we have called this method and specify the folder 'Examples' whose java files is to be combined and the path of jar file where we want to create the jar file.

Here is the code for Java Jar File Function:

import java.util.jar.*;

public class CreateJar {
  public static int buffer = 10240;
  protected void createJarArchive(File jarFile, File[] listFiles) {
    try {
      byte b[] new byte[buffer];
      FileOutputStream fout = new FileOutputStream(jarFile);
      JarOutputStream out = new JarOutputStream(fout, new Manifest());
      for (int i = 0; i < listFiles.length; i++) {
        if (listFiles[i== null || !listFiles[i].exists()|| listFiles[i].isDirectory())
        JarEntry addFiles = new JarEntry(listFiles[i].getName());

        FileInputStream fin = new FileInputStream(listFiles[i]);
        while (true) {
          int len =, 0, b.length);
          if (len <= 0)
          out.write(b, 0, len);
      System.out.println("Jar File is created successfully.");
    catch (Exception ex) {}
  public static void main(String[]args){
    CreateJar jar=new CreateJar();
    File folder = new File("C://Answers//Examples");
      File[] files = folder.listFiles();
    File file=new File("C://Answers//Examples//Examples.jar");
    jar.createJarArchive(file, files);


Posted on: October 30, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null