需要注意的是,仅对字符串长度较大时有作用,字符串较短时由于base64编码的缘故可能会大于原有字符串长度~
public static String gzip(String string) {
String result = null;
if (StringUtils.isBlank(string)) {
return result;
}
ByteArrayOutputStream out = null;
GZIPOutputStream gzip = null;
try {
out = new ByteArrayOutputStream();
gzip = new GZIPOutputStream(out);
gzip.write(string.getBytes(StandardCharsets.UTF_8));
result = Base64.encode(out.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (gzip != null) {
gzip.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String unGzip(String string) {
String result = null;
if (StringUtils.isBlank(string)) {
return result;
}
ByteArrayOutputStream out = null;
ByteArrayInputStream in = null;
GZIPInputStream ungzip = null;
byte[] bytes = Base64.decode(string);
try {
out = new ByteArrayOutputStream();
in = new ByteArrayInputStream(bytes);
ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = ungzip.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
result = out.toString(StandardCharsets.UTF_8.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ungzip != null) {
ungzip.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
本文由 GY 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2023/08/28 14:00