Java字符串的壓縮與解壓縮的兩種方法
應用場景
當字符串太長,
需要將字符串值存入數(shù)據(jù)庫時,如果字段長度不夠,則會出現(xiàn)插入失??;
或者需要進行Http傳輸時,由于參數(shù)長度過長造成http傳輸失敗等。
字符串壓縮與解壓方法
方法一:用 Java8中的gzip
/**
* 使用gzip壓縮字符串
* @param str 要壓縮的字符串
* @return
*/
public static String compress(String str) {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzip != null) {
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
/**
* 使用gzip解壓縮
* @param compressedStr 壓縮字符串
* @return
*/
public static String uncompress(String compressedStr) {
if (compressedStr == null) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = null;
GZIPInputStream ginzip = null;
byte[] compressed = null;
String decompressed = null;
try {
compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
in = new ByteArrayInputStream(compressed);
ginzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = ginzip.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
decompressed = out.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ginzip != null) {
try {
ginzip.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return decompressed;
}
方法二:用org.apache.commons.codec.binary.Base64
/**
* 使用org.apache.commons.codec.binary.Base64壓縮字符串
* @param str 要壓縮的字符串
* @return
*/
public static String compress(String str) {
if (str == null || str.length() == 0) {
return str;
}
return Base64.encodeBase64String(str.getBytes());
}
/**
* 使用org.apache.commons.codec.binary.Base64解壓縮
* @param compressedStr 壓縮字符串
* @return
*/
public static String uncompress(String compressedStr) {
if (compressedStr == null) {
return null;
}
return Base64.decodeBase64(compressedStr);
}
注意事項
在web項目中,服務器端將加密后的字符串返回給前端,前端再通過ajax請求將加密字符串發(fā)送給服務器端處理的時候,在http傳輸過程中會改變加密字符串的內(nèi)容,導致服務器解壓壓縮字符串發(fā)生異常:
java.util.zip.ZipException: Not in GZIP format
解決方法:
在字符串壓縮之后,將壓縮后的字符串BASE64加密,在使用的時候先BASE64解密再解壓即可。
到此這篇關(guān)于Java字符串的壓縮與解壓縮的兩種方法的文章就介紹到這了,更多相關(guān)Java字符串壓縮內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Spring @Bean 相同加載順序不同結(jié)果不同的問題記錄
本文主要探討了在Spring 5.1.3.RELEASE版本下,當有兩個全注解類定義相同類型的Bean時,由于加載順序不同,最終生成的Bean實例也會不同,文章通過分析ConfigurationClassPostProcessor的執(zhí)行過程,解釋了BeanDefinition的加載和覆蓋機制,感興趣的朋友一起看看吧2025-02-02
SpringCloud中的熔斷監(jiān)控HystrixDashboard和Turbine示例詳解
HystrixDashboard是用于實時監(jiān)控Hystrix性能的工具,展示請求響應時間和成功率等數(shù)據(jù),本文介紹了如何配置和使用HystrixDashboard和Turbine進行熔斷監(jiān)控,包括依賴添加、啟動類配置和測試流程,感興趣的朋友一起看看吧2024-09-09

