Java GZIP压缩的使用

为了减小服务器负担,传递字符串内容通常要进行压缩,同时也能增强传输的速度,在java中GZIP压缩基本实现代码如下:

 

	/**
	 * 将压缩字符串解压为字符串
	 * @param file 压缩文件
	 * @return 解压为字符串
	 * @throws Exception
	 */
	public static String deCompressString(File file) throws Exception{
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream byteOut2 = new ByteArrayOutputStream();
		decompress(fis, byteOut2);
		byte[] bs = byteOut2.toByteArray();
		return new String(bs,"utf-8");
	}
	/**
	 * 将字符串压缩到一个file中
	 * @param str 字符串
	 * @param file 压缩到的file
	 * @throws Exception
	 */
	public static void compressString(String str,File file) throws Exception{
		FileOutputStream fos = new FileOutputStream(file);
		ByteArrayInputStream byteIn = new ByteArrayInputStream(str.getBytes("utf-8"));
		compress(byteIn, fos);
	}
	/**
	 * GZIP数据压缩
	 * @param is
	 * @param os
	 * @throws Exception
	 */
	public static void compress(InputStream is, OutputStream os) throws Exception {
		GZIPOutputStream gos = new GZIPOutputStream(os);
		int count;
		byte data[] = new byte[BUFFER];
		while ((count = is.read(data, 0, BUFFER)) != -1) {
			gos.write(data, 0, count);
		}
		gos.finish();
		gos.flush();
		gos.close();
	}
	/**
	 * GZIP数据解压缩
	 * @param is
	 * @param os
	 * @throws Exception
	 */
	public static void decompress(InputStream is, OutputStream os) throws Exception {
		GZIPInputStream gis = new GZIPInputStream(is);
		int count;
		byte data[] = new byte[BUFFER];
		while ((count = gis.read(data, 0, BUFFER)) != -1) {
			os.write(data, 0, count);
		}
		gis.close();
	}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值