您的位置 首页 java

java实现长字符串压缩和还原方法供大家参考

由于需要将一个较大的参数值 进行数据库存储,而存储后在进行读取时会由于该表的存储量很大,这个值会导致加大IO

我们在 java 中能否使用一个比较高压缩的方式或进行编码、加密也可,或者某种手段将这个 字符串 的长度进行压缩

下面是我的实现方法:

1 压缩方法源码

2 解压方法源码

/**

* 使用gzip进行解压缩

* @param compressedStr

* @return

*/

public static String gunzip(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;

}

/**

* 使用zip进行解压缩

* @param compressed 压缩后的文本

* @return 解压后的字符串

*/

public static final String unzip(String compressedStr) {

if (compressedStr == null) {

return null;

}

ByteArrayOutputStream out = null;

ByteArrayInputStream in = null;

ZipInputStream zin = null;

String decompressed = null;

try {

byte[] compressed = new sun.misc.BASE64Decoder()

.decodeBuffer(compressedStr);

out = new ByteArrayOutputStream();

in = new ByteArrayInputStream(compressed);

zin = new ZipInputStream(in);

zin.getNextEntry();

byte[] buffer = new byte[1024];

int offset = -1;

while ((offset = zin.read(buffer)) != -1) {

out.write(buffer, 0, offset);

}

decompressed = out.toString();

} catch (IOException e) {

decompressed = null;

} finally {

if (zin != null) {

try {

zin.close();

} catch (IOException e) {

}

}

if (in != null) {

try {

in.close();

} catch (IOException e) {

}

}

if (out != null) {

try {

out.close();

} catch (IOException e) {

}

}

}

return decompressed;

}

3 测试方法

/**

* 测试方法

* @param args

*/

public static void main(String[] args) {

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 1000; i++) {

// 长度为2000的一个字符串

sb. append (“ab”);

}

String jiaStr = gzip(sb.toString());

System.out.println(jiaStr);

String jieStr = gunzip(jiaStr);

System.out.println(jieStr);

}

请大家多多关注我的头条号,谢谢大家。

文章来源:智云一二三科技

文章标题:java实现长字符串压缩和还原方法供大家参考

文章地址:https://www.zhihuclub.com/185525.shtml

关于作者: 智云科技

热门文章

网站地图