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 java.io.BufferedOutputStream; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.util.List; /** * Tar 压缩器 * * @author 夜雨 * @version 2024-06-30 19:48 */ public class TarCompressor extends Compressor { @Override public void run(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)); try (TarArchiveOutputStream tarOutputStream = new TarArchiveOutputStream(new BufferedOutputStream(nonClosing(toStream)))) { 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 { resetProgress(); } } }