henryz2003
henryz2003

Reputation: 11

How do you append to the end of a gzipped file in Java?

Here is what I've tried

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;


public class GZIPCompression {

    public static void main(String[] args) throws IOException {
        File file = new File("gziptest.zip");

        try ( OutputStream os = new GZIPOutputStream(new FileOutputStream(file, true))) {
            os.write("test".getBytes());
        }

        try ( GZIPInputStream inStream = new GZIPInputStream(new FileInputStream(file))) {
            while (inStream.available() > 0) {
                System.out.print((char) inStream.read());
            }
        }
    }
}

Based on what I've read, this should append "test" to the end of gziptest.zip, but when I run the code, the file doesn't get modified at all. The strange thing is that if I change FileOutputStream(file, true) to FileOutputStream(file, false), the file does get modified, but its original contents are overriden which is of course not what I want.

I am using JDK 14.0.1.

Upvotes: 0

Views: 288

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35106

A couple of things here.

  1. Zip and GZip are different.. If you are doing a gzip test, your file should have the extension .gz, not .zip
  2. To properly append "test" to the end of the gzip data, you should first use a GZIPInputStream to read in from the file, then tack "test" onto the uncompressed text, and then send it back out through GZipOutputStream

Upvotes: 3

Related Questions