`

【java】字符串的压缩转码base64

    博客分类:
  • java
 
阅读更多
由于客户端与服务端之间采用web service的方式进行传输。
然后如果传送大型的字符串的时候就会出现缓慢的问题。
比如我们测试了。在2w条数据。大概60多m的字符串传输的时候要花费7--8秒时间。
所以就考虑到使用压缩和转码的方式进行传输。
对方接受到数据先反转码,然后再进行解压。
一下是自己使用java进行完成的功能。

package com.duduli.li.zip;

import java.io.ByteArrayOutputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

import org.apache.commons.codec.binary.Base64;


public class ZipWithZlib {
	
//	压缩字符串
	public static String compressData(String data) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			DeflaterOutputStream zos = new DeflaterOutputStream(bos);
			zos.write(data.getBytes());
			zos.close();
			return new String(getenBASE64inCodec(bos.toByteArray()));
		} catch (Exception ex) {
			ex.printStackTrace();
			return "ZIP_ERR";
		}
	}
	
//	使用apche codec对数组进行encode
	public static String getenBASE64inCodec(byte [] b) {
		if (b == null)
			return null;
		return new String((new Base64()).encode(b));
	}
	
	
	
	
//	base64转码为string
	
	public static byte[] getdeBASE64inCodec(String s) {
		if (s == null)
			return null;
		return new Base64().decode(s.getBytes());
	}
	
//	解码字符串
	public String decompressData(String encdata) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			InflaterOutputStream zos = new InflaterOutputStream(bos);
			zos.write(getdeBASE64inCodec(encdata)); 
//			byte [] b = encdata.getBytes();
//			int len = b.length;
//			zos.write(b, 0, len);
//			zos.write(getdeBASE64(encdata.getBytes()),0,(encdata.getBytes()).length);
			zos.close();
			return new String(bos.toByteArray());
		} catch (Exception ex) {
			ex.printStackTrace();
			return "UNZIP_ERR";
		}
	}
	
	
	public static void main(String[] args) {
		ZipWithZlib zwz = new ZipWithZlib();
		String compString = zwz.compressData("中华人民共和国");
		System.out.println(compString);
		
		String decompString = zwz.decompressData(compString);
		System.out.println(decompString);
		
	}
}


其中base64的转码需要导入apache的codec包,不能使用sun的那个包。

原因是sun的那个包会在文件过大的时候自己加入回车换行。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics