package io.github.jshipit; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.compress.utils.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class TarManager { public TarManager() { } public void tar(String name, File... files) throws IOException { try (TarArchiveOutputStream out = getTarArchiveOutputStream(name)){ for (File file : files){ addToArchive(out, file, "."); } } } public void untar(String in, File out) throws IOException { try (TarArchiveInputStream fin = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(in)))){ TarArchiveEntry entry; while ((entry = fin.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File curfile = new File(out, entry.getName()); File parent = curfile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } IOUtils.copy(fin, new FileOutputStream(curfile)); } } } private TarArchiveOutputStream getTarArchiveOutputStream(String name) throws IOException { TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(name)); taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR); taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); taos.setAddPaxHeadersForNonAsciiNames(true); return taos; } private void addToArchive(TarArchiveOutputStream out, File file, String dir) throws IOException { String entry = dir + File.separator + file.getName(); if (file.isFile()){ out.putArchiveEntry(new TarArchiveEntry(file, entry)); try (FileInputStream in = new FileInputStream(file)){ IOUtils.copy(in, out); } out.closeArchiveEntry(); } else if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null){ for (File child : children){ addToArchive(out, child, entry); } } } else { System.out.println(file.getName() + " is not supported"); } } }