
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.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;


public class EditJarTest {

	static void createTempJar(String originalJar, String copyJar) throws FileNotFoundException, IOException {
		//Make a teporary copy of the jar file
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(originalJar));
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(copyJar));
		int b;
		while ((b = in.read()) != -1) {
			out.write(b);
		}
		in.close();
		out.close();
	}

	static byte[] getContentFileToAdd(String filePath) throws FileNotFoundException, IOException {
		//Read the content of the file to add and put it in a byte array
		FileInputStream textFileIn = new FileInputStream(filePath);
		byte[] data = new byte[textFileIn.available()];
		textFileIn.read(data);
		textFileIn.close();
		return data;
	}

	public static void main(String[] args) throws FileNotFoundException, IOException {

		//The path to the original jar
		String jarName = "/home/issam/test.jar";

		//The path to the temporary jar
		String jarNameTmp = "/home/issam/test.jar.tmp";

		createTempJar(jarName, jarNameTmp);

		//The path to the file to add
		String fileToAdd = "/home/issam/tata.jar";

		byte[] data = getContentFileToAdd(fileToAdd);

		//We use the class JarFile to read from the temporary jar file
		JarFile jarFile = new JarFile(jarNameTmp);

		//We retrieve all the entries (files) in the jar file
		Enumeration<JarEntry> entries = jarFile.entries();

		//we will use JarOutputStream to create a new jar file
		JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(jarName));

		//Read each entry in the tmp jar and write it in the original jar,
		//because the creation of a new JarOutputStream delete any previous content

		while (entries.hasMoreElements()) {
			JarEntry entry = entries.nextElement();
			if (!entry.isDirectory()) {
				byte[] entryData = new byte[(int)entry.getSize()];
				jarOut.putNextEntry(entry);

				InputStream entryIn = jarFile.getInputStream(entry);
				while (entryIn.read(entryData) != -1) {
					jarOut.write(entryData);
				}
				jarOut.closeEntry();
				entryIn.close();
			}
		}

		//add the new file to the jar
		jarOut.putNextEntry(new JarEntry(new File(fileToAdd).getName()));
		jarOut.write(data);
		jarOut.closeEntry();

		jarOut.close();
		new File(jarNameTmp).delete();
	}
}
