Files
timi-compress/src/main/java/com/imyeyu/compress/TarDecompressor.java
Timi afcc902cbf
Some checks failed
CI/CD / build-deploy (pull_request) Failing after 1m31s
v0.0.1
2026-04-01 14:09:24 +08:00

74 lines
1.8 KiB
Java

package com.imyeyu.compress;
import com.imyeyu.io.IO;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Tar 解压器
*
* @author 夜雨
* @version 2024-06-30 19:48
*/
public class TarDecompressor extends Decompressor {
@Override
public void run(File fromFile, String toPath) throws Exception {
initByteProgress(readTotalSize(fromFile));
try {
super.run(fromFile, toPath);
} finally {
resetProgress();
}
}
@Override
public void run(InputStream fromStream, String toPath) throws Exception {
try (TarArchiveInputStream tarInputStream = new TarArchiveInputStream(nonClosing(fromStream))) {
TarArchiveEntry entry;
boolean processed = false;
while ((entry = tarInputStream.getNextEntry()) != null) {
String path = IO.fitPath(toPath) + entry.getName();
if (entry.isDirectory()) {
IO.dir(path);
} else {
File toFile = IO.file(path);
try (OutputStream outputStream = IO.getOutputStream(toFile)) {
transfer(tarInputStream, outputStream);
outputStream.flush();
}
handleFile(toFile);
processed = true;
}
}
if (processed) {
finishProgress();
}
}
}
/**
* 读取压缩包解压总字节数
*
* @param fromFile 压缩文件
* @return 总字节数
* @throws Exception 读取失败
*/
private long readTotalSize(File fromFile) throws Exception {
long totalSize = 0L;
try (InputStream inputStream = IO.getInputStream(fromFile); TarArchiveInputStream tarInputStream = new TarArchiveInputStream(inputStream)) {
TarArchiveEntry entry;
while ((entry = tarInputStream.getNextEntry()) != null) {
if (!entry.isDirectory()) {
totalSize += entry.getSize();
}
}
}
return totalSize;
}
}