How to Create Jar File using Java


 

How to Create Jar File using Java

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

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.io.*;
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())
      System.out.println();
        JarEntry addFiles = new JarEntry(listFiles[i].getName());
        addFiles.setTime(listFiles[i].lastModified());
        out.putNextEntry(addFiles);

        FileInputStream fin = new FileInputStream(listFiles[i]);
        while (true) {
          int len = fin.read(b, 0, b.length);
          if (len <= 0)
            break;
          out.write(b, 0, len);
        }
        fin.close();
      }
      out.close();
      fout.close();
      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);
  }
}

Ads