Attilah
Attilah

Reputation: 17930

Creating a JAR file programmatically

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.

Upvotes: 2

Views: 6057

Answers (3)

Bozho
Bozho

Reputation: 597016

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

Look here for info about the parameters you can set.

Upvotes: 3

Gabor Garami
Gabor Garami

Reputation: 1265

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.

Upvotes: 1

McDowell
McDowell

Reputation: 108859

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.

Upvotes: 0

Related Questions