前言:
最近开发一个文件中转管理系统,需要先把PowerBI数据湖中的数据生成Excel后放中转系统,待消费方(SAP系统)消费完以后再把这些数据删除掉。因为从PowerBI生成的Excel文件有点大,数据传输经常会出现超时的情况,于是便决定先把生成的Excel压缩成.rar文件后再传输。所以这里需要使用到文件的压缩和解压技术。
JAVA压缩解压文件代码:
pom.xml
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version> </dependency>GZipUtil.java
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 * 堆代码 duidaima.com * @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; } }
总结:
以上就是基于JAVA实现的文件压缩和解压的代码,谢谢阅读。