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解密再解壓即可。
到此這篇關于Java字符串的壓縮與解壓縮的兩種方法的文章就介紹到這了,更多相關Java字符串壓縮內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決mybatisplus MetaObjectHandler 失效的問題
本文主要介紹了解決mybatisplus MetaObjectHandler 失效的問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02
Java Chassis3過載狀態(tài)下的快速失敗解決分析
本文解密了Java Chassis 3快速失敗相關的機制和背后故事,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
從零搭建SpringBoot+MyBatisPlus快速開發(fā)腳手架
這篇文章主要為大家介紹了從零搭建SpringBoot+MyBatisPlus快速開發(fā)腳手架示例教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06

