tags:

views:

175

answers:

1

Hello

I'm trying to modify a file in a zip-file using java.util.net As direct modification of a file is not possible and I want to modify only one single file, I just create a new zip file containing basically the content of the template and replace the specific file, at least that's the plan.

Here are the most important lines of my attempt:

Enumeration<? extends ZipEntry> entries = zif.entries();
while (entries.hasMoreElements()) {
ZipEntry currentEntry = entries.nextElement();
if (!currentEntry.isDirectory() && currentEntry.getSize() >0 && currentEntry.getCompressedSize() > 0)
{
    System.out.println(currentEntry.getName() + ": " + currentEntry.getSize() + "-" + currentEntry.getMethod());
    if (currentEntry.getName() != "file_i_want_to_change")
    {
        try {
            this.zos.putNextEntry(currentEntry);  // HERE the exception is thrown
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
}

Info: zif = ZipFile, correctly instanciated and opened from a existing file; zos = ZipOutputStream, correctly instanciated for a new file.

This is the exception that is thrown:

java.util.zip.ZipException: invalid entry size (expected 39 but got 0 bytes)
at java.util.zip.ZipOutputStream.closeEntry(ZipOutputStream.java:228)
at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:144)
at TestClass.replace(TestClass.java:117)
at TestClass.main(TestClass.java:10)

whereas TestClass:117 is the line with the comment, that's where it fails.

The funny thing is that the System.out.println in the piece of code is working perfectly and without any file reporting to be 0-sized.

Does anybody see a mistake I might have made?

Any idea is appreciated.

Thanks in advance and best regards

+3  A: 

Just writing the ZipEntry to the stream is not enough, you still need to write the contents as well.

        this.zos.putNextEntry(new ZipEntry(currentEntry));
        int len;
        while ((len = zis.read(buf)) >= 0)
        {
           zos.write(buf, 0, len);
        }

Full example here

objects
this would in fact mean that ZipEntry only contains information _about_ the file, but not the _file contents_ itself (that's what the input stream is for and it might be the reason why getInputStream() is in ZipFile and not in ZipEntry... Could've seen that on my own, damn. Will try again and check back... Thanks!!
Atmocreations
Atmocreations
thanks, glad I could help
objects