August 3rd, 1999, 11:37 AM
Hi,
I want to create a jar file programmatically.I should not use DOS prompt to create the jar file.In my coding/program,I have to create a jar file and embed all my classes in it.Is it possible?.I think we can do.Can anyone suggest the track of it.Thanking you in advance.
varbsjava
August 4th, 1999, 12:32 AM
Hi,
You have a look at the java.util.jar.* and java.util.zip.* package in Java2 for details on this.
I will write a small sample program for this.
import java.util.jar.*;
import java.util.*;
import java.util.zip.*;
import java.io.*;
public class TestJar{
public static void main(String[] args){
try{
CRC32 c = new CRC32();//For creating the checksum
Deflater d = new Deflater(Deflater.DEFAULT_COMPRESSION,true);//For compressing the data
FileInputStream fis = new FileInputStream("A.java");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while(fis.available() != 0){
baos.write(fis.read());
}
byte[] b = null;
b = baos.toByteArray();
byte[] b1 = new byte[b.length];
while(d.needsInput()) {
d.setInput(b);
}
d.finish();
int i = d.deflate(b1,0,b1.length);//Compressing the data and getting the compressed size
c.update(b,0,b.length);//Getting the checksum value.
FileOutputStream fos = new FileOutputStream("Test.jar");
JarOutputStream jos = new JarOutputStream(fos,new Manifest());
JarEntry je = new JarEntry("A.java");
je.setComment("Sample Jar");
long cSize = 722L;//This should be the original file size.
je.setSize(cSize);
je.setCompressedSize(i);
je.setCrc(c.getValue());
je.setMethod(JarEntry.DEFLATED);
System.out.println("Putting into the stream");
jos.putNextEntry(je);
jos.write(b,0,b.length);
jos.close();
}catch(java.io.IOException e){
System.out.println(e);
}
}
You have to usee the JarOutputStream to create a new Jar file. For creating it, u have to create a JarEntry for each and every file in the Jar. Then we have to calculate the CompressionSize,Checksum using the Deflater and CRC32 classes. Then put the jar entry into the JarOuputStream after setting the above value for the jar and then write the contents of the file into the JarFile. Compression will take place depending upon the compression type mentioned in the setMethod(). Then close all the streams. Now u will get a new Jar file.
I hope this basic one will help u. If u have any queries mail me.
regards,
arun...