package test;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipUtils {
public static String TAG = GzipUtils.class.getName();
public static Logger logger = Logger.getLogger(TAG);
public static byte[] gzip(byte[] bArr) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bArr.length);
GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gZIPOutputStream.write(bArr);
gZIPOutputStream.close();
byteArrayOutputStream.close();
return byteArrayOutputStream.toByteArray();
} catch (IOException unused) {
logger.warning("GzipUtils: failed to gzip");
return bArr;
}
}
public static byte[] ungzip(byte[] bArr) {
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bArr);
GZIPInputStream gZIPInputStream = new GZIPInputStream(byteArrayInputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gZIPInputStream, StandardCharsets.UTF_8));
StringBuilder sb2 = new StringBuilder();
while (true) {
String readLine = bufferedReader.readLine();
if (readLine != null) {
sb2.append(readLine);
} else {
bufferedReader.close();
gZIPInputStream.close();
byteArrayInputStream.close();
return sb2.toString().getBytes();
}
}
} catch (IOException unused) {
logger.warning("GzipUtils: failed to ungzip");
return bArr;
}
}
public static void main(String[] args) {
String data = "raw data: hello world!";
byte[] gzipByte = gzip(data.getBytes());
String gzipData = new String(gzipByte,StandardCharsets.UTF_8);
logger.info("gzipData: " + gzipData);
String ungzipData = new String(ungzip(gzipByte));
logger.info("ungzipData: " + ungzipData);
}
}