Showing posts with label jar. Show all posts
Showing posts with label jar. Show all posts

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();
    }
}


12 October 2010

Shell: a script file to search a directory of Jars about which jar cointains which file?

Hi folks,

Today I am coming with some shell script that is useful if you want to need to know from a group of Jars in certain directory which one of them contains a certain file (Java class)

#! /bin/sh

path=$1
segment=$2

if [ -z "$path" ] || [ -z "$segment" ]
then
echo "Usage: $0 <path> <segment>"
exit
fi

for jar in $path/*.jar ; do echo " *** $jar *** " ; jar tf $jar| grep --color=always $segment; done;