Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZipOutputStream doesn't write file contents

Tags:

java

stream

zip

I need to zip data that is coming from one stream and put zipped data to another. Here is the code that operates with files (MyOutputStream is a simple FileOutputStream wrapper used for debug purposes). This code works fine.

        ZipOutputStream jos = new ZipOutputStream( new MyOutputStream(new FileOutputStream(zipFileName)));
        jos.setLevel(Deflater.DEFAULT_COMPRESSION);
        jos.putNextEntry(new ZipEntry("test.txt"));
        FileInputStream in = new FileInputStream("test.txt");

        int len;
        while ((len = in.read(buffer)) > 0){
             jos.write(buffer, 0, len);
        }
        jos.closeEntry();
        jos.close();

In my real application I have to deal with more complex streams. In fact, streams are used for CORBA interop. However, data is successfully read. But when I try to do jos.write(buffer, 0, len); no data is written to the output stream that is underlying ZipOutputStream. However, zip file headers, entries comments and central directory are written successfully so I get absolutely valid zip with only one exception that files are empty.

Maybe anyone had seen this behavior before? Any help is appreciated.

EDIT Here is my real code as it may be useful:

String fileName = fullSourcePath.substring(fullSourcePath.lastIndexOf('\\') + 1, fullSourcePath.length());
WrapperOutputStream out = new WrapperOutputStream(newexchangeStream64);
ZipOutputStream jos = new ZipOutputStream(out);
jos.setLevel(Deflater.NO_COMPRESSION);

jos.putNextEntry(new ZipEntry(fileName));
jos.setComment("Comment");
IDLDataHolder data = new IDLDataHolder();
LongHolder dataAmount = new LongHolder();
LongHolder written = new LongHolder();

while (true) {
    exchangeStream64.Read(data, READ_AMOUNT, dataAmount);
    if (0 == dataAmount.value) {
        break;
    }

    jos.write(data.value, (int)dataAmount.value, (int)written.value);
}
jos.closeEntry();
jos.close();
like image 452
Ola Avatar asked Feb 24 '26 00:02

Ola


1 Answers

LongHolder written = new LongHolder();

while (true) {
    exchangeStream64.Read(data, READ_AMOUNT, dataAmount);
    if (0 == dataAmount.value) {
        break;
    }

    jos.write(data.value, (int)dataAmount.value, (int)written.value);
}

It may be just a copy&paste mistake here, but the last parameter of jos.write is always 0. That is the amount of bytes to write from the array.

like image 84
Hendrik Brummermann Avatar answered Feb 26 '26 12:02

Hendrik Brummermann