Java JarOutputStream create jar file

Description

Java JarOutputStream create jar file



import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.Deflater;

public class Main {
  public static void main(String[] args) throws Exception {
    Manifest manifest = getManifest();
    String jarFileName = "Main.jar";
    String[] jarEntries = new String[] {"images/logo.bmp","com/demo2s/Test.class"};


    try (JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(
        new FileOutputStream(jarFileName)), manifest)) {
      jos.setLevel(Deflater.BEST_COMPRESSION);
      for (int i = 0; i < jarEntries.length; i++) {
        File entryFile = new File(jarEntries[i]);
        if (!entryFile.exists()) {
          return;
        }/*from  w  w  w  .j  av  a 2  s.  c om*/
        JarEntry je = new JarEntry(jarEntries[i]);
        jos.putNextEntry(je);
        addEntryContent(jos, jarEntries[i]);
        jos.closeEntry();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void addEntryContent(JarOutputStream jos, String entryFileName)
      throws IOException, FileNotFoundException {
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
        entryFileName));
    byte[] buffer = new byte[1024];
    int count = -1;
    while ((count = bis.read(buffer)) != -1) {
      jos.write(buffer, 0, count);
    }

    bis.close();
  }

  public static Manifest getManifest() {
    Manifest manifest = new Manifest();
    Attributes mainAttribs = manifest.getMainAttributes();
    mainAttribs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    mainAttribs.put(Attributes.Name.MAIN_CLASS, "com.demo2s.Test");
    mainAttribs.put(Attributes.Name.SEALED, "true");

    Map<String, Attributes> attribsMap = manifest.getEntries();

    Attributes a1 = getAttribute("Sealed", "false");
    attribsMap.put("com/demo2s/", a1);

    Attributes a2 = getAttribute("Content-Type", "image/bmp");
    attribsMap.put("images/logo.bmp", a2);

    return manifest;
  }

  public static Attributes getAttribute(String name, String value) {
    Attributes a = new Attributes();
    Attributes.Name attribName = new Attributes.Name(name);
    a.put(attribName, value);
    return a;
  }
}



PreviousNext

Related