Android实现压缩字符串的方法示例
前言
Android端可以对字符串进行压缩,我们在进行大量简单文本传输时,可以先压缩字符串再发送。接收端接收后再解压。也可以将字符串压缩后存入数据库中,下面话不多说了,来一起看看详细的介绍吧。
使用到的类库
GZIPOutputStream
代码示例
importjava.io.ByteArrayInputStream; importjava.io.ByteArrayOutputStream; importjava.io.IOException; importjava.util.zip.GZIPInputStream; importjava.util.zip.GZIPOutputStream; publicclassStrZipUtil{ /** *@paraminput需要压缩的字符串 *@return压缩后的字符串 *@throwsIOExceptionIO */ publicstaticStringcompress(Stringinput)throwsIOException{ if(input==null||input.length()==0){ returninput; } ByteArrayOutputStreamout=newByteArrayOutputStream(); GZIPOutputStreamgzipOs=newGZIPOutputStream(out); gzipOs.write(input.getBytes()); gzipOs.close(); returnout.toString("ISO-8859-1"); } /** *@paramzippedStr压缩后的字符串 *@return解压缩后的 *@throwsIOExceptionIO */ publicstaticStringuncompress(StringzippedStr)throwsIOException{ if(zippedStr==null||zippedStr.length()==0){ returnzippedStr; } ByteArrayOutputStreamout=newByteArrayOutputStream(); ByteArrayInputStreamin=newByteArrayInputStream(zippedStr .getBytes("ISO-8859-1")); GZIPInputStreamgzipIs=newGZIPInputStream(in); byte[]buffer=newbyte[256]; intn; while((n=gzipIs.read(buffer))>=0){ out.write(buffer,0,n); } //toString()使用平台默认编码,也可以显式的指定如toString("GBK") returnout.toString(); } }
红米手机测试输出
08-0913:16:53.38832248-32267/com.rustfisher.ndkprojD/rustApp:开始存入数据库ori1len=304304 08-0913:16:53.41832248-32267/com.rustfisher.ndkprojD/rustApp:已存入数据库ori1len=304304,耗时约37ms 08-0913:16:53.41832248-32267/com.rustfisher.ndkprojD/rustApp:开始压缩ori1len=304304 08-0913:16:53.43832248-32267/com.rustfisher.ndkprojD/rustApp:压缩完毕zip1len=1112,耗时约19ms 08-0913:16:53.43832248-32267/com.rustfisher.ndkprojD/rustApp:存压缩后的数据进数据库zip1.length=1112 08-0913:16:53.44832248-32267/com.rustfisher.ndkprojD/rustApp:压缩后的数据已进数据库zip1.length=1112,耗时约8ms 08-0913:16:53.44832248-32267/com.rustfisher.ndkprojD/rustApp:解压开始 08-0913:16:53.48832248-32267/com.rustfisher.ndkprojD/rustApp:解压完毕耗时约36ms
存储时间受存储字符串的长度影响。字符串长度与存储耗时正相关。
荣耀手机测试
08-0910:38:42.75923075-23109/com.rustfisherD/rustApp:开始压缩ori1len=304304 08-0910:38:42.76423075-23109/com.rustfisherD/rustApp:压缩完毕zip1len=1112 08-0910:38:42.76423075-23109/com.rustfisherD/rustApp:解压开始 08-0910:38:42.78923075-23109/com.rustfisherD/rustApp:解压完毕
此例中,荣耀压缩耗时约5ms,解压耗时约25ms。
可以看出,压缩后与原长度之比1112/304304,约0.365%
压缩和解压缩耗时视手机情况而定。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。