How do i programatically copy contents of a Jar file into another jar file?

Davanum Srinivas

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

public class Main {

    public static void main(String[] args) throws Exception {

        // Create file descriptors for the jar and a temp jar.
        File jarFile = new File(args[0]);

        // Open the jar file.
        JarFile         jar     = new JarFile(jarFile);
        JarOutputStream tempJar =
            new JarOutputStream(new FileOutputStream(args[1]));

        // Allocate a buffer for reading entry data.
        byte[] buffer = new byte[1024];
        int    bytesRead;

        for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) {

            // Get the next entry.
            JarEntry entry = (JarEntry) entries.nextElement();

            // Get an input stream for the entry.
            InputStream entryStream = jar.getInputStream(entry);

            // Read the entry and write it to the temp jar.
            tempJar.putNextEntry(entry);

            while ((bytesRead = entryStream.read(buffer)) != -1) {
                tempJar.write(buffer, 0, bytesRead);
            }
        }

        tempJar.close();
    }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact