04 March 2011

Using JAR API to create a JAR file

import java.io.*;
import java.util.jar.*;

public class Main 
{
    /**
     * convert some class to a JAR file 
     * @param bytecode    bytecode of the class file
     * @param fullClassName    fully qualified java class name written as: com/example/Hello.class
     * @return array of bytes that represent the jar file returned
     * @throws IOException
     */
    public static byte[] getJARfromBytecode(byte[] bytecode, String fullClassName) throws IOException
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bytecode.length);
        JarOutputStream jarOutputStream = new JarOutputStream(outputStream);
        JarEntry entry = new JarEntry(fullClassName);
        jarOutputStream.putNextEntry(entry);
        jarOutputStream.write(bytecode);
        jarOutputStream.close();
        outputStream.close();
        byte[] ret = outputStream.toByteArray();
        return ret;
    }
    
    public static void main(String[] args) throws FileNotFoundException, IOException 
    {
        byte[] data = getJARfromBytecode(BytecodeHelper.getbytecodeData("Hello"), "pkg/Hello.class");// getbytecodeData retruns some get the contents of a `.class` file as byte array
        FileOutputStream fos = new FileOutputStream("/home/mhewedy/xyz.jar");
        fos.write(data);
        fos.close();
    }
}


Post a Comment