Compress directory to tar.gz with Commons Compress

后端 未结 6 1403
终归单人心
终归单人心 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:43

    I ended up doing the following:

    public URL createTarGzip() throws IOException {
        Path inputDirectoryPath = ...
        File outputFile = new File("/path/to/filename.tar.gz");
    
        try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                GzipCompressorOutputStream gzipOutputStream = new GzipCompressorOutputStream(bufferedOutputStream);
                TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(gzipOutputStream)) {
    
            tarArchiveOutputStream.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
            tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
    
            List files = new ArrayList<>(FileUtils.listFiles(
                    inputDirectoryPath,
                    new RegexFileFilter("^(.*?)"),
                    DirectoryFileFilter.DIRECTORY
            ));
    
            for (int i = 0; i < files.size(); i++) {
                File currentFile = files.get(i);
    
                String relativeFilePath = new File(inputDirectoryPath.toUri()).toURI().relativize(
                        new File(currentFile.getAbsolutePath()).toURI()).getPath();
    
                TarArchiveEntry tarEntry = new TarArchiveEntry(currentFile, relativeFilePath);
                tarEntry.setSize(currentFile.length());
    
                tarArchiveOutputStream.putArchiveEntry(tarEntry);
                tarArchiveOutputStream.write(IOUtils.toByteArray(new FileInputStream(currentFile)));
                tarArchiveOutputStream.closeArchiveEntry();
            }
            tarArchiveOutputStream.close();
            return outputFile.toURI().toURL();
        }
    }
    

    This takes care of the some of the edge cases that come up in the other solutions.

提交回复
热议问题