package cn.com.chinamoney.cometd.common.util; import org.apache.commons.codec.binary.Base64; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.zip.*; /** * 使用zip、gzip对字符串进行压缩、解压缩 ; 使用apache的basee64加密、解密 * (使用 commons-codec-1.11.jar) * * 加密类BASE64Encoder被org.apache.commons.codec.binary.Base64替代了,所以不推荐使用 * JDK1.8提供最新可以正式使用的Base64类,可以用java.util.Base64.getEncoder().encodeToString("字符串内容")来生成base64码了。 * Createy by fenglei.ma on 9/11/2018.16:10 */ public class Base64Zip { private static final String CHARSET = "UTF-8"; private static org.slf4j.Logger log = LoggerFactory.getLogger(Base64Zip.class); public static void main(String[] args) throws IOException { // 字符串超过一定的长度 String str = new String("{\"ProductCode\": \"q\",\"HighestPrice\": \"w\",\"LowestPrice\": \"e\",\"OpeningPrice\": \"r\",\"LatestPrice\": \"123456789\",\"PriceChangePoint\": \"中中中中中0\",\"PriceChangeRatio\":\"0.0000\",\"ValueDate\":1535009734533,\"MarketDataUpdatedTime\": 1509706096000,\"TradeVolumeFlag\": \"0\",\"DateConfirmed\": 1509638400000,\"TakerDirection\":\"S\",\"CurrencyPairCode\": \"USD/CNY\",\"CfetsUnifiedCode\": \"CNY=CFHC\",\"DealMarketDateType\": \"2\",\"TradingMode\": \"9\"}"); // String str = "{\"ed\":\"20170121 09:44:01\",\"sd\":\"20161021 09:44:01\",\"cd\":\"72016102116762039687\"}"; System.out.println("\n原始的字符串为------->" + str); float len0 = str.length(); System.out.println("原始的字符串长度为------->" + len0); String ys = gzipString(str); System.out.println("\n压缩后的字符串为----->" + ys); float len1 = ys.length(); System.out.println("压缩后的字符串长度为----->" + len1); String jy = ungzipString(ys); System.out.println("\n解压缩后的字符串为--->" + jy); System.out.println("解压缩后的字符串长度为--->" + jy.length()); System.out.println("\n压缩比例为" + len1 / len0); //判断 if (str.equals(jy)) { System.out.println("先压缩再解压以后字符串和原来的是一模一样的"); } } /** * 用zip方式将字符串压缩成Base64 * * @return */ public static String zipString(String primStr) { if (primStr == null || primStr.length() == 0) { return primStr; } ByteArrayOutputStream out = null; ZipOutputStream zout = null; try { out = new ByteArrayOutputStream(); zout = new ZipOutputStream(out); zout.putNextEntry(new ZipEntry("0")); zout.write(primStr.getBytes(Charset.forName(CHARSET))); zout.closeEntry(); // return new BASE64Encoder().encode(out.toByteArray()); return new Base64().encodeToString(out.toByteArray()); } catch (IOException e) { log.error("对字符串进行加压加密操作失败:", e); return primStr; } finally { if (zout != null) { try { zout.close(); } catch (IOException e) { log.error("对字符串进行加压加密操作,关闭zip操作流失败:", e); } } } } /** * 用gzip方式将字符串压缩成Base64 * * @return */ public static final String unzipString(String compressedStr) { if (compressedStr == null) { return null; } ByteArrayOutputStream out = null; ByteArrayInputStream in = null; ZipInputStream zin = null; String decompressed = null; try { // byte[] compressed = new BASE64Decoder().decodeBuffer(compressedStr); byte[] compressed = new Base64().decode(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(CHARSET); } catch (IOException e) { log.error("对字符串进行解密解压操作失败:", e); decompressed = null; } finally { try { out.close(); } catch (IOException e) { log.error("对字符串进行解密解压操作,关闭压缩流失败:", e); } } return decompressed; } /** * 用zip方式压缩成Base64的字符串进行 解压缩 * * @param primStr * @return */ public static String gzipString(String primStr) { if (primStr == null || primStr.length() == 0) { return primStr; } ByteArrayOutputStream out = null; GZIPOutputStream gout = null; try { out = new ByteArrayOutputStream(); gout = new GZIPOutputStream(out); gout.write(primStr.getBytes(CHARSET)); gout.flush(); } catch (IOException e) { log.error("对字符串进行加压加密操作失败:", e); return null; } finally { if (gout != null) { try { gout.close(); } catch (IOException e) { log.error("对字符串进行加压加密操作,关闭gzip操作流失败:", e); } } } // return new BASE64Encoder().encode(out.toByteArray()); return new Base64().encodeToString(out.toByteArray()); } /** * 用gzip方式将压缩成Base64的字符串进行 解压缩 * * @param compressedStr * @return */ public static final String ungzipString(String compressedStr) { if (compressedStr == null) { return null; } ByteArrayOutputStream out = null; ByteArrayInputStream in = null; GZIPInputStream gin = null; String decompressed = null; try { // byte[] compressed = new BASE64Decoder().decodeBuffer(compressedStr); byte[] compressed = new Base64().decode(compressedStr); out = new ByteArrayOutputStream(); in = new ByteArrayInputStream(compressed); gin = new GZIPInputStream(in); byte[] buffer = new byte[1024]; int offset = 0; while ((offset = gin.read(buffer)) != -1) { out.write(buffer, 0, offset); } decompressed = out.toString(CHARSET); } catch (IOException e) { log.error("对字符串进行解密解压操作失败:", e); decompressed = null; } finally { try { out.close(); } catch (IOException e) { log.error("对字符串进行解密解压操作,关闭压缩流失败:", e); } } return decompressed; } /** * 使用 apache basee64加密 * * @param msg * @return * @throws UnsupportedEncodingException */ public static String encodeBase64String(String msg) throws UnsupportedEncodingException { return Base64.encodeBase64String(msg.getBytes(CHARSET)); } /** * 使用 apache basee64解密 * * @param msg * @return * @throws UnsupportedEncodingException */ public static String decodeBase64(String msg) throws UnsupportedEncodingException { return new String(Base64.decodeBase64(msg), CHARSET); } }