`
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class TestController {
public static byte[] compress(String str) {
if (StringUtils.isEmpty(str)) return null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
} catch ( Exception e) {
e.printStackTrace();
}
return out.toByteArray();
}
public static String uncompressToString(byte[] bytes) {
if (bytes == null || bytes.length == 0) return null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
try {
GZIPInputStream ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toString(String.valueOf(StandardCharsets.UTF_8));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String json = "{\"i\":20241009,\"n\":\"张三丰\",\"g\":18,\"s\":0,\"d\":\"北戴河\"}";
byte[] compress = compress(json);
System.out.println("JSON to Byte: " + Arrays.toString(compress));
String uncompressed = uncompressToString(compress);
System.out.println("Byte to JSON : " + uncompressed);
}
}
`
标签:java,String,json,new,Gzip,import,byte,out From: https://www.cnblogs.com/dawndefend/p/18454488