import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* @author cheng.tang
*/
@Slf4j
public class ZipUtils {
/**
* 使用gzip进行压缩
*
* @param waitingEncodingTxt
* @return
*/
public static String gzip(String waitingEncodingTxt) throws IOException {
if (StringUtils.isBlank(waitingEncodingTxt)) {
return "";
}
GZIPOutputStream gzip = null;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
gzip = new GZIPOutputStream(out);
gzip.write(waitingEncodingTxt.getBytes());
return Base64.getEncoder().encodeToString(out.toByteArray());
} catch (Exception e) {
log.warn("{}", e.getMessage(), e);
throw e;
} finally {
if (gzip != null) {
try {
gzip.close();
} catch (Exception ignored) {
}
}
}
}
/**
* 使用gzip进行解压缩
*
* @param compressedTxt
* @return
*/
public static String gunzip(String compressedTxt) {
if (StringUtils.isBlank(compressedTxt)) {
return "";
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = null;
GZIPInputStream ginzip = null;
try {
byte[] compressed = Base64.getDecoder().decode(compressedTxt);
in = new ByteArrayInputStream(compressed);
ginzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int offset;
while ((offset = ginzip.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
return out.toString();
} catch (IOException e) {
log.warn("{}", e.getMessage(), e);
return compressedTxt;
} finally {
if (ginzip != null) {
try {
ginzip.close();
} catch (IOException ignored) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException ignored) {
}
}
try {
out.close();
} catch (IOException ignored) {
}
}
}
}
网友评论