packagecom.zhao.algorithm.tree;import java.io.*;import java.util.*;/*** AUTHOR :zhao
* 日期:/2/17 17:42
* 赫夫曼编码 压缩与解压缩, 他是无损压缩*/
public classHuffmanCode {public static voidmain(String[] args) {//start 赫夫曼编码 解码
String msg="Man proposes,God disposes.";byte[] bytes =msg.getBytes();
System.out.println("压缩前长度 :"+bytes.length);//进行赫夫曼编码压缩
byte[] b =huffmanZip(bytes);
System.out.println("压缩后长度 :"+b.length);//使用赫夫曼编码进行解码
byte[] newBytes =decode(huffCodes,b);
System.out.println(newString(newBytes));//end ---------// //user.dir指定了当前的路径//String src=System.getProperty("user.dir")+"\\haffman.bmp";// //这里的压缩名后缀随便起//String dst="haffman.god";//try {//zipFile(src, dst);//} catch (IOException e) {//e.printStackTrace();//}//try {//unZip(dst, "haffman2.bmp");//} catch (Exception e) {//e.printStackTrace();//}
}/*** 文件的解压
*@paramsrc
*@paramdst
*@throwsException*/
public static void unZip(String src,String dst) throwsException {//创建一个输入流
InputStream is = newFileInputStream(src);
ObjectInputStream ois= newObjectInputStream(is);//读取byte数组
byte[] b = (byte[]) ois.readObject();//读取赫夫曼编码表
Map codes = (Map) ois.readObject();
ois.close();
is.close();//解码
byte[] bytes =decode(codes, b);//创建一个输出流
OutputStream os = newFile
java 字符串 无损压缩算法_使用赫夫曼编码对字符串和文件进行压缩和解压缩(无损压缩)...