package com.imyeyu.compress; import com.imyeyu.io.IO; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.util.List; /** * Gzip 压缩器 * 当前实现保持与原行为一致,实际输出为 tar.gz * * @author 夜雨 * @version 2024-06-30 19:40 */ public class GZipCompressor extends Compressor { /** * 创建压缩器 * * @param fromPath 源路径 * @return 压缩器 */ public static GZipCompressor from(String fromPath) { return new GZipCompressor().of(fromPath); } /** * 创建压缩器 * * @param fromFile 源文件 * @return 压缩器 */ public static GZipCompressor from(File fromFile) { return new GZipCompressor().of(fromFile); } @Override protected void toStream(String fromPath, OutputStream toStream) throws Exception { File fromFile = new File(fromPath); List files = IO.listFile(fromFile); String basePath = files.getFirst().getParentFile().getAbsolutePath(); initByteProgress(IO.calcSize(fromFile)); GzipCompressorOutputStream gzipOutputStream = new GzipCompressorOutputStream(new BufferedOutputStream(nonClosing(toStream))); TarArchiveOutputStream tarOutputStream = null; try { tarOutputStream = new TarArchiveOutputStream(gzipOutputStream); for (File sourceFile : files) { String name = sourceFile.getAbsolutePath().substring(basePath.length() + 1); TarArchiveEntry tarEntry = new TarArchiveEntry(sourceFile, normalizeEntryName(name)); tarOutputStream.putArchiveEntry(tarEntry); try (InputStream inputStream = IO.getInputStream(sourceFile)) { transfer(inputStream, tarOutputStream); } tarOutputStream.closeArchiveEntry(); handleFile(sourceFile); } tarOutputStream.finish(); finishProgress(); } finally { if (tarOutputStream != null) { tarOutputStream.close(); } else { gzipOutputStream.close(); } resetProgress(); } } }