GZip 压缩解压 工具类 [ GZipUtil ]
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version> </dependency>
package com.app.core.util; import lombok.extern.log4j.Log4j2; import org.apache.commons.codec.CharEncoding; import org.apache.commons.codec.binary.Base64; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; @Log4j2 public class GZipUtil { /** * 压缩GZip * * @return String */ public static String gZip(String input) { byte[] bytes = null; GZIPOutputStream gzip = null; ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); gzip = new GZIPOutputStream(bos); gzip.write(input.getBytes(CharEncoding.UTF_8)); gzip.finish(); gzip.close(); bytes = bos.toByteArray(); bos.close(); } catch (Exception e) { log.error("压缩出错:", e); } finally { try { if (gzip != null) gzip.close(); if (bos != null) bos.close(); } catch (final IOException ioe) { log.error("压缩出错:", ioe); } } return Base64.encodeBase64String(bytes); } /** * 解压GZip * * @return String */ public static String unGZip(String input) { byte[] bytes; String out = input; GZIPInputStream gzip = null; ByteArrayInputStream bis; ByteArrayOutputStream bos = null; try { bis = new ByteArrayInputStream(Base64.decodeBase64(input)); gzip = new GZIPInputStream(bis); byte[] buf = new byte[1024]; int num; bos = new ByteArrayOutputStream(); while ((num = gzip.read(buf, 0, buf.length)) != -1) { bos.write(buf, 0, num); } bytes = bos.toByteArray(); out = new String(bytes, CharEncoding.UTF_8); gzip.close(); bis.close(); bos.flush(); bos.close(); } catch (Exception e) { log.error("解压出错:", e); } finally { try { if (gzip != null) gzip.close(); if (bos != null) bos.close(); } catch (final IOException ioe) { log.error("解压出错:", ioe); } } return out; } }
相关推荐
-
JSON工具类 java
2019-1-12
-
Java 多线程 下载 java
2019-1-12
-
Excel 工具类 备选 java
2019-1-13
-
opencsv 工具类 [ CsvUtil ] java
2019-1-12
-
java二维码编码&解码 java
2019-1-8
-
监听器 在线人数统计 java
2019-1-8
-
推送消息工具类 java
2019-1-13
-
RESTful API 编写规范 java
2019-1-8
-
Http请求工具 java
2019-1-7
-
java生成验证码 java
2019-1-8