Search code examples
javajarzipinputstreamzipoutputstream

how to replacing some files within a certain directory inside a jar file?


I'm having the problem of replacing or updating some files within a certain directory inside a jar file.

I've read a few post already. The code (the JarUpdater Class) given at this link Updating .JAR's contents from code

is being very helpful for me to understand the role and the use of ZipInputStream, ZipOutputStream and ZipEntry, etc..

However, when I run it,

  1. I have an EOF Exception

[EDITED by mk7: I found out the jar file was corrupted after I went through it 20 times or so. So after I replaced the jar file with a new one, the EOF Exception went away. The other two problems below still remains unsolved]

  1. these two new xml files only get copied to the "root directory" of the jar file.

  2. these two new xml files NEVER replaced the two original files inside a directory called /conf.

Which lines of code should I change in order to replace the xml files with the new ones?

With the System.out.println, I did see that the while loop steps through every directory and compare at every file as expected. A new temp jar was also created as expected... I thought the statement "notInFiles = false" would take care of my need but it's NOT.

How do I step into the /conf and only replace those two files and NOT leave a copy at the root of the jar file?

What am I missing? Thanks for any insight!

Below are the code from that link.

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class JarUpdater {
public static void main(String[] args) {

    File[] contents = {new File("abc.xml"),
            new File("def.xml")};

    File jarFile = new File("xyz.jar");

    try {
        updateZipFile(jarFile, contents);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public static void updateZipFile(File jarFile,
                                 File[] contents) throws IOException {
    // get a temp file
    File tempFile = File.createTempFile(jarFile.getName(), null);
    // delete it, otherwise you cannot rename your existing zip to it.
    tempFile.delete();
    System.out.println("tempFile is " + tempFile);
    boolean renameOk=jarFile.renameTo(tempFile);
    if (!renameOk)
    {
        throw new RuntimeException("could not rename the file     "+jarFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
    }
    byte[] buf = new byte[1024];

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(jarFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (File f : contents) {
            System.out.println("f is " + f);
            if (f.getName().equals(name)) {
                // that file is already inside the jar file
                notInFiles = false;
                System.out.println("file already inside the jar file");
                break;
            }
        }
        if (notInFiles) {
            System.out.println("name is " + name);
            System.out.println("entry is " + entry);
            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(name));
            // Transfer bytes from the ZIP file to the output file
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }
    // Close the streams
    zin.close();
    // Compress the contents
    for (int i = 0; i < contents.length; i++) {
        InputStream in = new FileInputStream(contents[i]);
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(contents[i].getName()));
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry
        out.closeEntry();
        in.close();
    }
    // Complete the ZIP file
    out.close();
    tempFile.delete();
}
}

Solution

  • In your first cycle (while loop) where you copy the entries which you don't want to replace you don't close the entries in the output zip file. Add out.closeEntry(); like this:

    // Add ZIP entry to output stream.
    out.putNextEntry(new ZipEntry(name));
    // Transfer bytes from the ZIP file to the output file
    int len;
    while ((len = zin.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    // ADD THIS LINE:
    out.closeEntry();
    

    Also when you check if an entry is to be replaced, you should compare it to a full path, not just to the name of the file. For example if you want to replace abc.xml which is in the /conf folder, you should compare the entry name to "/conf/abc.xml" and not to "abc.xml".

    To properly check if an entry is to be replaced:

    String name = entry.getName();
    boolean notInFiles = true;
    for (File f : contents) {
        System.out.println("f is " + f);
        if (name.equals("/conf/" + f.getName()) {
            // that file is already inside the jar file
            notInFiles = false;
            System.out.println("file already inside the jar file");
            break;
        }
    }
    

    And when you add the entries to the output which are the replaced files, you also have to specify the entry name having full path, e.g. "/conf/abc.xml" and not just "abc.xml" because it would put "abc.xml" in the root of the output zip.

    To do this, start the entry name with "/conf/" like this:

    // Add ZIP entry to output stream.
    out.putNextEntry(new ZipEntry("/conf/" + contents[i].getName()));