您好,登錄后才能下訂單哦!
這篇文章給大家介紹Java中怎么壓縮與解壓縮字符串,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
/** * 使用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壓縮字符串 * @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項目中,服務(wù)器端將加密后的字符串返回給前端,前端再通過ajax請求將加密字符串發(fā)送給服務(wù)器端處理的時候,在http傳輸過程中會改變加密字符串的內(nèi)容,導(dǎo)致服務(wù)器解壓壓縮字符串發(fā)生異常:
java.util.zip.ZipException: Not in GZIP format
在字符串壓縮之后,將壓縮后的字符串BASE64加密,在使用的時候先BASE64解密再解壓即可。
關(guān)于Java中怎么壓縮與解壓縮字符串就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。