Posts tagged ‘jAVA’

julio 23, 2010

Generar un ejecutable jar desde un programa

Ejemplo de como generar un ejecutable jar desde un programa.

import java.io.IOException;
/**
 * @author Leyer
 */
public class JTest {
	public static void main(String[] args) throws java.io.FileNotFoundException, IOException {
		java.io.File MANIFEST = new java.io.File("/home/leyer/MANIFEST.MF");
		java.util.jar.Manifest manifest = null;
		if(MANIFEST.exists())
		manifest= new java.util.jar.Manifest(new java.io.FileInputStream(MANIFEST));
		else System.err.println("Manifest no found!");try {
		if(manifest!=null){
		java.io.File fileJar = new java.io.File("/home/leyer/jar.jar");
		java.util.jar.JarOutputStream jarOutputStream = new java.util.jar.JarOutputStream(new  java.io.FileOutputStream(fileJar),manifest);
		java.io.File testfile = new java.io.File("/package/file.class");
		final java.util.jar.JarEntry jarEntry = new java.util.jar.JarEntry(testfile.getAbsolutePath());
		jarOutputStream.putNextEntry(jarEntry);
		java.io.FileInputStream filereader = new  java.io.FileInputStream(testfile);
		final int buffersize = 1024; 
		byte buffer[] = new byte[buffersize]; 
		int readcount = 0; 
		while ((readcount = filereader.read(buffer, 0, buffersize)) >= 0) { 
			if (readcount > 0) { 
				jarOutputStream.write(buffer, 0, readcount); 
			}
		}
		jarOutputStream.flush();
		jarOutputStream.finish();
		System.out.println("Created jar file: "+fileJar.getName());
		}
	} catch (java.io.FileNotFoundException e) {e.printStackTrace();
	} catch (IOException e) {e.printStackTrace();
		}
	}
}