开发者

java.util.zip: putNextEntry

开发者 https://www.devze.com 2022-12-26 05:30 出处:网络
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 basic

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消