前言
Android端可以對(duì)字符串進(jìn)行壓縮,我們?cè)谶M(jìn)行大量簡(jiǎn)單文本傳輸時(shí),可以先壓縮字符串再發(fā)送。接收端接收后再解壓。也可以將字符串壓縮后存入數(shù)據(jù)庫(kù)中,下面話不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹吧。
使用到的類庫(kù)
GZIPOutputStream
代碼示例
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.util.zip.GZIPInputStream;import java.util.zip.GZIPOutputStream;public class StrZipUtil { /** * @param input 需要壓縮的字符串 * @return 壓縮后的字符串 * @throws IOException IO */ public static String compress(String input) throws IOException { if (input == null || input.length() == 0) { return input; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzipOs = new GZIPOutputStream(out); gzipOs.write(input.getBytes()); gzipOs.close(); return out.toString("ISO-8859-1"); } /** * @param zippedStr 壓縮后的字符串 * @return 解壓縮后的 * @throws IOException IO */ public static String uncompress(String zippedStr) throws IOException { if (zippedStr == null || zippedStr.length() == 0) { return zippedStr; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(zippedStr .getBytes("ISO-8859-1")); GZIPInputStream gzipIs = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = gzipIs.read(buffer)) >= 0) { out.write(buffer, 0, n); } // toString()使用平臺(tái)默認(rèn)編碼,也可以顯式的指定如toString("GBK") return out.toString(); }}紅米手機(jī)測(cè)試輸出
08-09 13:16:53.388 32248-32267/com.rustfisher.ndkproj D/rustApp: 開始存入數(shù)據(jù)庫(kù) ori1 len=30430408-09 13:16:53.418 32248-32267/com.rustfisher.ndkproj D/rustApp: 已存入數(shù)據(jù)庫(kù) ori1 len=304304 , 耗時(shí)約37 ms08-09 13:16:53.418 32248-32267/com.rustfisher.ndkproj D/rustApp: 開始?jí)嚎s ori1 len=30430408-09 13:16:53.438 32248-32267/com.rustfisher.ndkproj D/rustApp: 壓縮完畢 zip1 len=1112 , 耗時(shí)約19 ms08-09 13:16:53.438 32248-32267/com.rustfisher.ndkproj D/rustApp: 存壓縮后的數(shù)據(jù)進(jìn)數(shù)據(jù)庫(kù) zip1.length=111208-09 13:16:53.448 32248-32267/com.rustfisher.ndkproj D/rustApp: 壓縮后的數(shù)據(jù)已進(jìn)數(shù)據(jù)庫(kù) zip1.length=1112 , 耗時(shí)約8 ms08-09 13:16:53.448 32248-32267/com.rustfisher.ndkproj D/rustApp: 解壓開始08-09 13:16:53.488 32248-32267/com.rustfisher.ndkproj D/rustApp: 解壓完畢 耗時(shí)約36 ms
存儲(chǔ)時(shí)間受存儲(chǔ)字符串的長(zhǎng)度影響。字符串長(zhǎng)度與存儲(chǔ)耗時(shí)正相關(guān)。
榮耀手機(jī)測(cè)試
08-09 10:38:42.759 23075-23109/com.rustfisher D/rustApp: 開始?jí)嚎s ori1 len=30430408-09 10:38:42.764 23075-23109/com.rustfisher D/rustApp: 壓縮完畢 zip1 len=111208-09 10:38:42.764 23075-23109/com.rustfisher D/rustApp: 解壓開始08-09 10:38:42.789 23075-23109/com.rustfisher D/rustApp: 解壓完畢
此例中,榮耀壓縮耗時(shí)約5ms,解壓耗時(shí)約25ms。
可以看出,壓縮后與原長(zhǎng)度之比 1112/304304, 約0.365%
壓縮和解壓縮耗時(shí)視手機(jī)情況而定。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)VEVB武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注