34、哈夫曼树压缩文本和解压文本

  • 思路:

利用输入流和输出流进行文本的读出和写入,注意:压缩文件时会用到对象流(ObjectOutputStream写入文件),解压文件时,也会用到对象流(ObjectInputStream,读出文件)

  • 代码:
//压缩文件
	public void zipFile(String srcFile, String dstFile) {
		InputStream is = null;
		OutputStream os = null;
		ObjectOutputStream oos = null;
		
		try{
			is = new FileInputStream(srcFile);
			byte[] b = new byte[is.available()];
			is.read(b);
			byte[] hfmbytes = zip(b);
			
			os = new FileOutputStream(dstFile);
			oos = new ObjectOutputStream(os);
			oos.writeObject(hfmbytes);
			oos.writeObject(hashMap);
			
			
			
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println(e.getMessage());
		}finally {
			try {
				is.close();
				os.close();
				oos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	//解压文件
	public void deZip(String srcFile, String dstFile ) {
		InputStream is = null;
		ObjectInputStream ois = null;
		OutputStream os = null;
		
		try {
			is = new FileInputStream(srcFile);
			ois = new ObjectInputStream(is);
			byte[] hfmbytes = (byte[]) ois.readObject();
			Map<Byte, String> hfmMap = (Map<Byte, String>) ois.readObject();
			
			byte[] bytes1 = decode(hfmMap, hfmbytes);
			
			os = new FileOutputStream(dstFile);
			os.write(bytes1);
			
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e.getMessage());
		}finally {
			// TODO: handle finally clause
			try {
				is.close();
				ois.close();
				os.close();
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println(e.getMessage());
			}		
		}
		
	}

注:

1、对于已经压缩好的文件,再使用哈夫曼压缩,效果不明显(比如视频、ppt等)。

2、哈夫曼编码是按照字节进行编码的,适用于所有文件。

3、对于内容重复不明显的文本,压缩效果不明显。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值