Compress directory to tar.gz with Commons Compress

后端 未结 6 1390
终归单人心
终归单人心 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条回答
  •  梦毁少年i
    2020-12-30 06:46

    Something I use (via Files.walk API), you can chain gzip(tar(youFile));

    public static File gzip(File fileToCompress) throws IOException {
    
        final File gzipFile = new File(fileToCompress.toPath().getParent().toFile(),
                fileToCompress.getName() + ".gz");
    
        final byte[] buffer = new byte[1024];
    
        try (FileInputStream in = new FileInputStream(fileToCompress);
                GZIPOutputStream out = new GZIPOutputStream(
                        new FileOutputStream(gzipFile))) {
    
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }
    
        return gzipFile;
    }
    
    public static File tar(File folderToCompress) throws IOException, ArchiveException {
    
        final File tarFile = Files.createTempFile(null, ".tar").toFile();
    
        try (TarArchiveOutputStream out = (TarArchiveOutputStream) new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.TAR,
                        new FileOutputStream(tarFile))) {
    
            out.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
    
            Files.walk(folderToCompress.toPath()) //
                    .forEach(source -> {
    
                        if (source.toFile().isFile()) {
                            final String relatifSourcePath = StringUtils.substringAfter(
                                    source.toString(), folderToCompress.getPath());
    
                            final TarArchiveEntry entry = new TarArchiveEntry(
                                    source.toFile(), relatifSourcePath);
    
                            try (InputStream in = new FileInputStream(source.toFile())){
                                out.putArchiveEntry(entry);
    
                                IOUtils.copy(in, out);
    
                                out.closeArchiveEntry();
                            }
                            catch (IOException e) {
                                // Handle this better than bellow...
                                throw new RuntimeException(e);
                            }
                        }
                    });
    
        }
    
        return tarFile;
    }
    

提交回复
热议问题