targz工具类
public class TarGzUtils {
public static void extractTarGz(String sourceFilePath, String destDir) {
Path destPath = Paths.get(destDir);
if (!Files.exists(destPath)) {
FileUtil.mkdir(destDir);
}
try (InputStream fIn = Files.newInputStream(Paths.get(sourceFilePath));
BufferedInputStream bIn = new BufferedInputStream(fIn);
InputStream gzipIn = new GzipCompressorInputStream(bIn);
TarArchiveInputStream tIn = new TarArchiveInputStream(gzipIn)) {
TarArchiveEntry entry;
while ((entry = tIn.getNextTarEntry()) != null) {
Path targetPath = destPath.resolve(entry.getName());
if (entry.isDirectory()) {
Files.createDirectories(targetPath);
} else {
Files.copy(tIn, targetPath);
}
}
} catch (Exception e) {
throw new BusinessException("extractTarGz exception");
}
}
public static void compressFolderToTarGz(String sourceDir, String tarGzPath, String srcFileName) {
try (OutputStream fos = new FileOutputStream(tarGzPath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
GzipCompressorOutputStream gzos = new GzipCompressorOutputStream(bos);
TarArchiveOutputStream taos = new TarArchiveOutputStream(gzos)) {
addFolderToTar(new File(sourceDir), srcFileName, taos);
taos.finish();
System.out.println("压缩成功!");
} catch (IOException e) {
throw new BusinessException("compressFolderToTarGz exception");
}
}
private static void addFolderToTar(File folder, String base, TarArchiveOutputStream taos) throws IOException {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
String entryName = base + (base.length() == 0 ? "" : "/") + file.getName();
TarArchiveEntry entry = new TarArchiveEntry(file, entryName);
if (!file.isDirectory()) {
entry.setSize(file.length());
}
taos.putArchiveEntry(entry);
if (!file.isDirectory()) {
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
taos.write(buffer, 0, length);
}
}
}
taos.closeArchiveEntry();
if (file.isDirectory()) {
addFolderToTar(file, entryName, taos);
}
}
}
}
}
使用实例
@Test
void unzip(){
String zipFilePath = "/Users/temp/targz/900000535.tar.gz";
String unzipFilePath = "/Users/temp/targz/900000535";
TarGzUtils.extractTarGz(zipFilePath,unzipFilePath);
TarGzUtils.compressFolderToTarGz("/Users/temp/targz/900000535/900000535", "/Users/temp/targz/900000535/aaa.tar.gz", "900000535");
}