import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPUtils {
/**
* 字符串压缩为GZIP字节数组
*
* @param bytes
* @return
*/
public static byte[] compress(byte[] bytes) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out)) {
gzip.write(bytes);
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException("GZIP压缩error", e);
}
}
/**
* GZIP解压缩
*
* @param bytes
* @return
*/
public static byte[] uncompress(byte[] bytes) {
try (InputStream input = new ByteArrayInputStream(bytes);
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
GZIPInputStream ungzip = new GZIPInputStream(input);
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toByteArray();
} catch (Exception e) {
throw new RuntimeException("GZIP解压error", e);
}
}
}