Search code examples
javacompressiongziparchiveapache-commons

Creation gzip archive using Apache Commons Compress


I succeed to create gz archive with expected content, but how can I set the filename inside the archive?

I mean, if archive myfile.gz was created, the file inside it will be named "myfile", but I want to name it like source file, for example, "1.txt"

Current code:

public static void gz() throws FileNotFoundException, IOException {
    GZIPOutputStream out = null;
    String filePaths[] =  {"C:/Temp/1.txt","C:/Temp/2.txt"}; 
    try {
         out = new GZIPOutputStream(
              new BufferedOutputStream(new FileOutputStream("C:/Temp/myfile.gz")));

            RandomAccessFile f = new RandomAccessFile(filePaths[0], "r");
            byte[] b = new byte[(int)f.length()];
            f.read(b);
            out.write(b, 0, b.length);

            out.finish();
            out.close();
    } finally {
         if(out != null) out.close();
    }
}

Solution

  • GZip compresses a stream. Typically, when people use GZip with multiple files, they also use tar to munch them together. gzip archive with multiple files inside