Files
timi-compress/src/main/java/com/imyeyu/compress/ZipCompressor.java
Timi 56dec33c94
All checks were successful
CI/CD / build-deploy (pull_request) Successful in 14s
v0.0.2
2026-04-01 22:47:09 +08:00

74 lines
2.1 KiB
Java

package com.imyeyu.compress;
import com.imyeyu.io.IO;
import com.imyeyu.java.bean.CallbackArg;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Zip 压缩器
*
* @author 夜雨
* @version 2024-06-30 19:46
*/
public class ZipCompressor extends Compressor<ZipCompressor> {
/**
* 静态执行压缩
*
* @param fromPath 源路径
* @param toPath 目标文件路径
* @return 当前压缩器
* @throws Exception 压缩失败
*/
public static ZipCompressor run(String fromPath, String toPath) throws Exception {
return run(fromPath, toPath, null, null);
}
/**
* 静态执行压缩
*
* @param fromPath 源路径
* @param toPath 目标文件路径
* @param fileCallback 文件处理回调
* @param progressCallback 进度回调
* @return 当前压缩器
* @throws Exception 压缩失败
*/
public static ZipCompressor run(String fromPath, String toPath, CallbackArg<File> fileCallback, CallbackArg<Double> progressCallback) throws Exception {
return new ZipCompressor()
.fileCallback(fileCallback)
.progressCallback(progressCallback)
.run(fromPath, IO.file(toPath));
}
@Override
protected void doRun(String fromPath, OutputStream toStream) throws Exception {
File fromFile = new File(fromPath);
List<File> files = IO.listFile(fromFile);
String basePath = files.getFirst().getParentFile().getAbsolutePath();
initByteProgress(IO.calcSize(fromFile));
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(nonClosing(toStream)))) {
for (File sourceFile : files) {
String name = sourceFile.getAbsolutePath().substring(basePath.length() + 1);
zipOutputStream.putNextEntry(new ZipEntry(normalizeEntryName(name)));
try (InputStream inputStream = IO.getInputStream(sourceFile)) {
transfer(inputStream, zipOutputStream);
}
zipOutputStream.closeEntry();
handleFile(sourceFile);
}
zipOutputStream.finish();
finishProgress();
} finally {
resetProgress();
}
}
}