Files
timi-compress/src/main/java/com/imyeyu/compress/Compressor.java
Timi b56f4e8969
All checks were successful
CI/CD / build-deploy (pull_request) Successful in 13s
v0.0.3
2026-04-02 16:23:53 +08:00

121 lines
2.5 KiB
Java

package com.imyeyu.compress;
import com.imyeyu.io.IO;
import com.imyeyu.java.bean.timi.TimiException;
import java.io.File;
import java.io.OutputStream;
/**
* 抽象压缩器
*
* @param <T> 压缩器类型
* @author 夜雨
* @version 2024-06-30 10:34
*/
public abstract class Compressor<T extends Compressor<T>> extends AbstractRunner<T> {
/** 源路径 */
private String fromPath;
/**
* 绑定源路径
*
* @param fromPath 源路径
* @return 当前压缩器
*/
public T from(String fromPath) {
TimiException.required(fromPath, "not found fromPath");
this.fromPath = fromPath;
return self();
}
/**
* 绑定源文件
*
* @param fromFile 源文件
* @return 当前压缩器
*/
public T from(File fromFile) {
TimiException.required(fromFile, "not found fromFile");
return from(fromFile.getAbsolutePath());
}
/**
* 压缩到目标文件
*
* @param toFile 目标压缩文件
* @return 当前压缩器
* @throws Exception 压缩失败
*/
public T toFile(File toFile) throws Exception {
toFile(requireFromPath(), toFile);
return self();
}
/**
* 压缩到目标文件路径
*
* @param toPath 目标压缩文件路径
* @return 当前压缩器
* @throws Exception 压缩失败
*/
public T toFile(String toPath) throws Exception {
return toFile(IO.file(toPath));
}
/**
* 压缩到输出流
* 输出流由调用方管理
*
* @param toStream 目标输出流
* @return 当前压缩器
* @throws Exception 压缩失败
*/
public T toStream(OutputStream toStream) throws Exception {
toStream(requireFromPath(), toStream);
return self();
}
/**
* 获取已绑定的源路径
*
* @return 源路径
*/
protected String requireFromPath() {
TimiException.required(fromPath, "not found source");
return fromPath;
}
/**
* 执行压缩到目标文件
*
* @param fromPath 源路径
* @param toFile 目标压缩文件
* @throws Exception 压缩失败
*/
protected void toFile(String fromPath, File toFile) throws Exception {
try (OutputStream outputStream = IO.getOutputStream(toFile)) {
toStream(fromPath, outputStream);
outputStream.flush();
} catch (Exception exception) {
if (isInterrupt) {
IO.destroy(toFile);
}
throw exception;
}
if (isInterrupt) {
IO.destroy(toFile);
}
}
/**
* 执行压缩到输出流
*
* @param fromPath 源路径
* @param toStream 目标输出流
* @throws Exception 压缩失败
*/
protected abstract void toStream(String fromPath, OutputStream toStream) throws Exception;
}