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、對於內容重複不明顯的文本,壓縮效果不明顯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章