java 压缩类使用 Deflater 和 Inflater

本文介绍了使用Java的Deflater和Inflater类进行数据压缩与解压缩的过程,包括压缩比计算和输出字符串转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.zip.test;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class ZIPTest {

	 public static String percnet(double d,double e){  
	        double p = d/e;  
	        DecimalFormat nf = (DecimalFormat) NumberFormat.getPercentInstance();  
	        nf.applyPattern("00%"); //00表示小数点2位  
	        nf.setMaximumFractionDigits(2); //2表示精确到小数点后2位  
	        return nf.format(p);  
	    }  
	public static void main(String[] args) {
		String inputStr="hello world.fdsaadfsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
		try {
			byte[] outputStr = inputStr.getBytes("UTF-8");

			byte[] output =new byte[100];
			Deflater compress = new Deflater();
			compress.setInput(outputStr);
			compress.finish();
			int compressDataLength = compress.deflate(output);
			System.out.println(compressDataLength);
			
			//decompress
			Inflater decompress = new Inflater();
			byte[] input = new byte[100];
			decompress.setInput(output, 0, compressDataLength);
			int resultLength = decompress.inflate(input);
			System.out.println(resultLength);
			decompress.end();
			
			if (resultLength < compressDataLength) {
				System.out.println("负压缩比");
			}
			else {
				System.out.println(percnet( (double)compressDataLength , (double)resultLength));
			}
			System.out.println(new String(input, 0, resultLength,"UTF-8")  );
			
		} catch (Exception e) {
			e.printStackTrace();
		}
			 
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值