tags:

views:

535

answers:

3

I created a Jar file from my java code :

public void create() throws IOException{
  FileOutputStream stream = new FileOutputStream(this.packagePath);
  JarOutputStream out = new JarOutputStream(stream, new Manifest());
  out.close();
  //jarFile = new JarFile(new File(this.packagePath));
}

I get a META-INF directory, with a MANIFEST.MF file inside.

now, When I want to add a file to the jar file :

public void addFile(File file) throws IOException{

 //first, make sure the package already exists
 if(!file.exists()){
  throw new IOException("Make" +
    " sure the package file already exists.you might need to call the Package.create() " +
    "method first.");
 }

 FileOutputStream stream = new FileOutputStream(this.packagePath);
 JarOutputStream out = new JarOutputStream(stream);
 /*if(jarFile.getManifest()!=null){
  out = new JarOutputStream(stream,jarFile.getManifest());
 }else{
  out=new JarOutputStream(stream);
 }*/

 byte buffer[] = new byte[BUFFER_SIZE];     
 JarEntry jarEntry = new JarEntry(file.getName());
 jarEntry.setTime(file.lastModified());
 out.putNextEntry(jarEntry);

 //Write file to archive
    FileInputStream in = new FileInputStream(file);

    while (true) {
      int nRead = in.read(buffer, 0, buffer.length);
      if (nRead <= 0)
        break;
      out.write(buffer, 0, nRead);
    }
    in.close();  
    out.close();
}

when adding a file to the JAR archive using the above code, the META-INF directory with its MANIFEST.MF disappears and I get the newly added file.

I want to be able to add the file to the jar, and still get the manifest file. inside the manifest file, I want a line with the name of the newly added jar .

thanks.

+1  A: 
  1. include the ant.jar in your project classpath
  2. Jar jar = new Jar();
    //configure the jar object
    jar.execute();

Look here for info about the parameters you can set.

Bozho
+1 for code reuse
Alexander Pogrebnyak
A: 
FileOutputStream stream = new FileOutputStream(this.packagePath);

This line will create a new, empty file.

To edit a jar file, you will need to back up the old version and copy its entries into your new jar file.

McDowell
A: 

I think you cannot add a new entry, because you cannot open jar package for "append". I think you must create a new jar file and copying entries from old, and add your entries.

Gabor Garami