java gzip 压缩 解压缩

/**
  * 接收request中的流
  * 判断是否是gzip格式
  */
 public static InputStream validateGzip(HttpServletRequest request) {
  try {
   String contentType = request.getContentType();
   if (contentType != null && contentType.trim().length() > 0 && contentType.trim().equals("application/x-zip-compressed")) {
    return unGzip(request);
   }
   return request.getInputStream();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }
 /**
  * 解压gzip文件
  */
 public static InputStream unGzip(HttpServletRequest request) {
  try {
   GZIPInputStream gzip = new GZIPInputStream(request.getInputStream());
   byte[] buf = new byte[1024];
   int len;
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   while ((len = gzip.read(buf)) != -1) {
    baos.write(buf, 0, len);
   }
   byte[] b = baos.toByteArray();
   ByteArrayInputStream bs = new ByteArrayInputStream(b);
   baos.flush();
   baos.close();
   gzip.close();
   return new DataInputStream(bs);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }
//压缩gzip
Writer pw = Util.createGzipPw(request, response);
				pw.write(xmlinfo);
				pw.flush();
				pw.close();


// 將gzip文件寫入到流裏面
	public static PrintWriter createGzipPw(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/x-zip-compressed");
		response.addHeader("Content-disposition", "attachment; filename=\"data.zip\"");
		response.addHeader("Cache-Control", "no-cache");
		PrintWriter pw = new PrintWriter(new OutputStreamWriter(new GZIPOutputStream(response.getOutputStream()), "UTF-8"));
		return pw;
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值