Compress directory to tar.gz with Commons Compress

后端 未结 6 1410
终归单人心
终归单人心 2020-12-30 06:13

I\'m running into a problem using the commons compress library to create a tar.gz of a directory. I have a directory structure that is as follows.

parent/
          


        
6条回答
  •  忘掉有多难
    2020-12-30 06:32

    I haven't figured out what exactly was going wrong but a scouring of google caches I found a working example. Sorry for the tumbleweed!

    public void CreateTarGZ()
        throws FileNotFoundException, IOException
    {
        try {
            System.out.println(new File(".").getAbsolutePath());
            dirPath = "parent/childDirToCompress/";
            tarGzPath = "archive.tar.gz";
            fOut = new FileOutputStream(new File(tarGzPath));
            bOut = new BufferedOutputStream(fOut);
            gzOut = new GzipCompressorOutputStream(bOut);
            tOut = new TarArchiveOutputStream(gzOut);
            addFileToTarGz(tOut, dirPath, "");
        } finally {
            tOut.finish();
            tOut.close();
            gzOut.close();
            bOut.close();
            fOut.close();
        }
    }
    
    private void addFileToTarGz(TarArchiveOutputStream tOut, String path, String base)
        throws IOException
    {
        File f = new File(path);
        System.out.println(f.exists());
        String entryName = base + f.getName();
        TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName);
        tOut.putArchiveEntry(tarEntry);
    
        if (f.isFile()) {
            IOUtils.copy(new FileInputStream(f), tOut);
            tOut.closeArchiveEntry();
        } else {
            tOut.closeArchiveEntry();
            File[] children = f.listFiles();
            if (children != null) {
                for (File child : children) {
                    System.out.println(child.getName());
                    addFileToTarGz(tOut, child.getAbsolutePath(), entryName + "/");
                }
            }
        }
    }
    

提交回复
热议问题