Java字符串压缩和解压缩源码

2019-02-03  本文已影响0人  地主天敌

在做工程过程中,把做工程过程较好的代码片段做个收藏,下边资料是关于Java字符串压缩和解压缩的代码,希望能对大家有较大好处。

package com.util;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.util.zip.GZIPInputStream;

import java.util.zip.GZIPOutputStream;

public class ZipUtil {

  public static String compress(String str) throws IOException {

    if (str == null || str.length() == 0) {

      return str;

    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    GZIPOutputStream gzip = new GZIPOutputStream(out);

    gzip.write(str.getBytes());

    gzip.close();

    return out.toString("ISO-8859-1");

  }

  public static String uncompress(String str) throws IOException {

    if (str == null || str.length() == 0) {

      return str;

    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    ByteArrayInputStream in = new ByteArrayInputStream(str

        .getBytes("ISO-8859-1"));

    GZIPInputStream gunzip = new GZIPInputStream(in);

    byte[] buffer = new byte[256];

    int n;

    while ((n = gunzip.read(buffer)) >= 0) {

      out.write(buffer, 0, n);

    }

    return out.toString();

  }

  public static void main(String[] args) throws IOException {

  String str="%5B%7B%22lastUpdateTime%22%3A%222011-10-28+9%3A39%3A41%22%2C%22smsList%22%3A%5B%7B%22liveState%22%3A%221";

  System.out.println("原长度:"+str.length()); 

  System.out.println("压缩后:"+ZipUtil.compress(str).length()); 

    System.out.println("解压缩:"+ZipUtil.uncompress(ZipUtil.compress(str)));

  }

}

运行结果:

原长度:104

压缩后:95

上一篇 下一篇

猜你喜欢

热点阅读