欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java gzip 压缩 解压缩

程序员文章站 2024-03-14 09:08:52
...
/**
  * 接收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;
	}