码迷,mamicode.com
首页 > 其他好文 > 详细

String压缩 解压缩

时间:2015-01-28 21:24:38      阅读:376      评论:0      收藏:0      [点我收藏+]

标签:

数据传输时,有时需要将数据压缩和解压缩,本例使用GZIPOutputStream/GZIPInputStream实现。
1、使用ISO-8859-1作为中介编码,可以保证准确还原数据

2、字符编码确定时,可以在decompress方法最后一句中显式指定编码

package com.bcxin.business.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author suzhida 
 * String压缩/解压
 */
public class StringCompress {

	/**
	 * 压缩字符串
	 * 
	 * @param str
	 *            压缩的字符串
	 * @return 压缩后的字符串
	 */
	public static String compress(String str) {

		if (StringUtil.isEmpty(str)) {
			return str;
		}

		try {
			ByteArrayOutputStream bos = null;
			GZIPOutputStream os = null; // 使用默认缓冲区大小创建新的输出流
			byte[] bs = null;
			try {
				bos = new ByteArrayOutputStream();
				os = new GZIPOutputStream(bos);
				os.write(str.getBytes()); // 写入输出流
				os.close();
				bos.close();
				bs = bos.toByteArray();
				return new String(bs, "ISO-8859-1"); // 通过解码字节将缓冲区内容转换为字符串
			} finally {
				bs = null;
				bos = null;
				os = null;
			}
		} catch (Exception ex) {
			return str;
		}
	}

	/**
	 * 解压缩字符串
	 * 
	 * @param str
	 *            解压缩的字符串
	 * @return 解压后的字符串
	 */
	public static String decompress(String str) {

		if (StringUtil.isEmpty(str)) {
			return str;
		}

		ByteArrayInputStream bis = null;
		ByteArrayOutputStream bos = null;
		GZIPInputStream is = null;
		byte[] buf = null;
		try {
			bis = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
			bos = new ByteArrayOutputStream();
			is = new GZIPInputStream(bis); // 使用默认缓冲区大小创建新的输入流
			buf = new byte[1024];
			int len = 0;
			while ((len = is.read(buf)) != -1) { // 将未压缩数据读入字节数组
				// 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此byte数组输出流
				bos.write(buf, 0, len);
			}
			is.close();
			bis.close();
			bos.close();
			return new String(bos.toByteArray()); // 通过解码字节将缓冲区内容转换为字符串
		} catch (Exception ex) {
			return str;
		} finally {
			bis = null;
			bos = null;
			is = null;
			buf = null;
		}
	}

}


String压缩 解压缩

标签:

原文地址:http://blog.csdn.net/jerome_s/article/details/43239235

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!