0

I have a zip file which I want to convert to gzip and write it back to the filesystem. How can I do this?

I already have this code to compress a file to gzip:

private static void compressGzipFile(String file, String gzipFile) {
    try {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(gzipFile);
        GZIPOutputStream gzipOS = new GZIPOutputStream(fos);
        byte[] buffer = new byte[1024];
        int len;

        while ((len=fis.read(buffer)) != -1) {
            gzipOS.write(buffer, 0, len);
        }

        // Close resources
        gzipOS.close();
        fos.close();
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Now I need code to convert the zip file into a gzip file.

MTCoster
  • 5,868
  • 3
  • 28
  • 49
Ya Ko
  • 509
  • 2
  • 4
  • 19
  • You can't convert a zip file to a gzip file, because zip-files can contain files, while gzip doesn't. Do you want to gzip the zip file instead (which I doubt will be effective). – Mark Rotteveel Feb 14 '19 at 18:30

1 Answers1

-1

Why not just pipe a ZipInputStream directly into a GZIPOutputStream?

private static void convertZipToGzip(String zipFile, String gzipFile) {
    try (ZipInputStream zipIS = new ZipInputStream(file),
         GZIPOutputStream gzipOS = new GZIPOutputStream(gzipFile)) {
        zipIS.transferTo(gzipOS);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

This solution takes advantage of Java 9’s incredibly useful InputStream#transferTo(OutputStream). If you’re not yet using Java 9, you’ll need to manually copy the bytes from one stream to the other, or use Apache Commons IOUtils’ IOUtils.copy(InputStream, OutputStream).

MTCoster
  • 5,868
  • 3
  • 28
  • 49
  • the code in the answer take the zip file and compress it to gzip, I looking for code the take the zip content and compress it go gzip – Ya Ko Feb 14 '19 at 17:16