How to Compress/Decompress tar.gz files in java

前端 未结 7 1135
粉色の甜心
粉色の甜心 2020-12-02 17:05

Can anyone show me the correct way to compress and decompress tar.gzip files in java i\'ve been searching but the most i can find is either zip or gzip(alone).

7条回答
  •  孤街浪徒
    2020-12-02 17:17

    To extract the contents of .tar.gz format, I successfully use apache commons-compress ('org.apache.commons:commons-compress:1.12'). Take a look at this example method:

    public void extractTarGZ(InputStream in) {
        GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in);
        try (TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) {
            TarArchiveEntry entry;
    
            while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
                /** If the entry is a directory, create the directory. **/
                if (entry.isDirectory()) {
                    File f = new File(entry.getName());
                    boolean created = f.mkdir();
                    if (!created) {
                        System.out.printf("Unable to create directory '%s', during extraction of archive contents.\n",
                                f.getAbsolutePath());
                    }
                } else {
                    int count;
                    byte data[] = new byte[BUFFER_SIZE];
                    FileOutputStream fos = new FileOutputStream(entry.getName(), false);
                    try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
                        while ((count = tarIn.read(data, 0, BUFFER_SIZE)) != -1) {
                            dest.write(data, 0, count);
                        }
                    }
                }
            }
    
            System.out.println("Untar completed successfully!");
        }
    }
    

提交回复
热议问题