哈夫曼树与文件压缩和解压缩-解压


一、解压原理:
了解了压缩原理之后,要解压文件就是压缩文件的逆过程;拿昨天的例子来说,如果我们收到这样一串二进制1 1 01 1 1 01 00(昨天漏掉了一个问题,这里是9个0 1,每8个一个字节,那么剩下的那个0需要补7个0,构成一个完整的字节,这样才能写出文件)怎么解压出aabbac呢?很自然的想到,我们需要拿到对应的哈夫曼编码;a的编码是1,b的编码是01,c的编码是00;拿到这个编码后,我们开始对这个0 1串分割,先取出一个0或1,看是否有对应的编码,如上,我们先取第一个1,编码中有1的编码,对应a,那么把第一个1还原为a,接下来,再去一个0或1,得到1,编码中有1,对应a,那么还原为a,接下来去0,没有编码,取01对应b,把01还原为b......以此类推
有人会怀疑这样的正确性,不会解压错误吗?比如如果编码中有1 和11,那么11改怎么还原呢?是解析成两个1进行还原,还是解析成一个11进行还原呢?其实不用担心,这就是哈夫曼编码的优势,哈夫曼编码中不会出现这样的问题;不相信的话,你可以自己去检验下;
 
将这么多,其实很简单,就类似于情报的破解,我只要有密码本就可以了;而哈夫曼编码就是我们的密码本;
 
二、哈夫曼树文件解压实现:
文件的压缩和解压缩是两个相对独立的程序;所以,我们在把压缩数据写入文件之前,需要把该文件对应的哈夫曼编码一起写入文件,相当于解压时的密码本;
所以,昨天的压缩程序还少了一步,就是把编码写入压缩文件中;我们只需把每个字母对应的哈夫曼编码的长度以及所有字母对应的哈夫曼编码写入文件即可;
 
 
读取文件的时候,先读取每个哈夫曼编码的长度,在根据长度去分割写入的哈夫曼编码,同时把哈夫曼编码写入对应的位置即可;如上图所示,前面的96长度都是0,不需要分割哈夫曼编码;97的长度是1,则分割1,并把1存入对应的字符数组中;同时分割01,把01存储在字符数组的第98个位置;以此类推;
 
难点:处理不够8位01的写入,记得把补0的个数一起写入文件;
 
三、整个思路整理如下:
 
 
 
四、压缩工程源代码和解压缩工程源代码:
两个独立的工程,代码不共享;
用压缩工程压缩的文件,可以用解压缩的工程文件解压缩;
 
压缩工程源代码:
HuffmNode类和昨天的一样,就不上传了;
 
更改后的compress类:
[java]  view plain  copy
 
  1. package com.huaxin.compress;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.util.LinkedList;  
  7.   
  8. public class Compress {  
  9.       
  10.     public int [] times = new int[256];  
  11.     public String [] HuffmCodes=new String[256];  
  12.     public LinkedList<HuffmNode> list = new LinkedList<HuffmNode>();  
  13.     //统计次数  
  14.       
  15.     //初始化  
  16.     public Compress(){  
  17.         for (int i = 0; i < HuffmCodes.length; i++) {  
  18.             HuffmCodes[i]="";  
  19.         }  
  20.     }  
  21.       
  22.     public void countTimes(String path) throws Exception{  
  23.         //构造文件输入流  
  24.         FileInputStream fis = new FileInputStream(path);  
  25.         //读取文件  
  26.         int value=fis.read();  
  27.         while(value!=-1){  
  28.             times[value]++;  
  29.             value=fis.read();  
  30.         }  
  31.         //关闭流  
  32.         fis.close();  
  33.     }  
  34.       
  35.     //构造哈夫曼树  
  36.     public HuffmNode createTree(){  
  37.         //将次数作为权值构造森林  
  38.         for (int i = 0; i < times.length; i++) {  
  39.             if(times[i]!=0){  
  40.                 HuffmNode node = new HuffmNode(times[i],i);  
  41.                 //将构造好的节点加入到容器中的正确位置  
  42.                 list.add(getIndex(node), node);  
  43.             }  
  44.         }  
  45.           
  46.         //将森林(容器中的各个节点)构造成哈夫曼树  
  47.         while(list.size()>1) {  
  48.             //获取容器中第一个元素(权值最小的节点)  
  49.             HuffmNode firstNode =list.removeFirst();  
  50.             //获取中新的第一个元素,原来的第一个元素已经被移除了(权值次小的节点)  
  51.             HuffmNode secondNode =list.removeFirst();  
  52.             //将权值最小的两个节点构造成父节点  
  53.             HuffmNode fatherNode =  
  54.                     new HuffmNode(firstNode.getData()+secondNode.getData(),-1);  
  55.             fatherNode.setLeft(firstNode);  
  56.             fatherNode.setRight(secondNode);  
  57.             //父节点加入到容器中的正确位置  
  58.             list.add(getIndex(fatherNode),fatherNode);  
  59.         }  
  60.         //返回整颗树的根节点  
  61.         return list.getFirst();  
  62.     }  
  63.     //利用前序遍历获取编码表  
  64.     public void getHuffmCode(HuffmNode root,String code){  
  65.         //往左走,哈夫曼编码加0  
  66.         if(root.getLeft()!=null){  
  67.             getHuffmCode(root.getLeft(),code+"0");  
  68.         }  
  69.         //往右走,哈夫曼编码加1  
  70.         if(root.getRight()!=null){  
  71.             getHuffmCode(root.getRight(),code+"1");  
  72.         }  
  73.         //如果是叶子节点,返回该叶子节点的哈夫曼编码  
  74.         if(root.getLeft()==null && root.getRight()==null){  
  75. //          System.out.println(root.getIndex()+"的编码为:"+code);  
  76.             HuffmCodes[root.getIndex()]=code;  
  77.         }  
  78.     }  
  79.       
  80.     //压缩文件  
  81.     public void compress(String path,String destpath) throws Exception{  
  82.           
  83.           
  84.           
  85.         //构建文件输出流  
  86.         FileOutputStream fos = new FileOutputStream(destpath);  
  87.         FileInputStream fis = new FileInputStream(path);  
  88.         /**===============把码表写入文件================*/  
  89.         //将整个哈夫曼编码以及每个编码的长度写入文件  
  90.         String code ="";  
  91.         for (int i = 0; i < 256; i++) {  
  92.             fos.write(HuffmCodes[i].length());  
  93.             code+=HuffmCodes[i];  
  94.             fos.flush();  
  95.         }  
  96.         //把哈夫曼编码写入文件  
  97.           
  98. //      System.out.println("code="+code);  
  99.         String str1="";  
  100.         while(code.length()>=8){  
  101.             str1=code.substring(0, 8);  
  102.             int c=changeStringToInt(str1);  
  103. //          System.out.println(c);  
  104.             fos.write(c);  
  105.             fos.flush();  
  106.             code=code.substring(8);  
  107.         }  
  108.         //处理最后一个不为8的数  
  109.         int last=8-code.length();  
  110.         for (int i = 0; i <last; i++) {  
  111.             code+="0";  
  112.         }  
  113.         str1=code.substring(0, 8);  
  114.         int c=changeStringToInt(str1);  
  115.         fos.write(c);  
  116.         fos.flush();  
  117.           
  118.         /**===============将数据写入到文件中================*/  
  119.           
  120.         //读文件,并将对应的哈夫曼编码串接成字符串  
  121.         int value=fis.read();  
  122.         String str = "";  
  123.         while(value!=-1){  
  124.             str+=HuffmCodes[value];  
  125. //          System.out.println((char)value+":"+str);  
  126.             value=fis.read();  
  127.         }  
  128.         System.out.println(str);  
  129.         fis.close();  
  130.           
  131.             String s="";  
  132.             //将字符8位分割,对弈一个字节  
  133.             while(str.length()>=8){  
  134.                 s=str.substring(0, 8);  
  135.                 int b=changeStringToInt(s);  
  136. //              System.out.println(c);  
  137.                 fos.write(b);  
  138.                 fos.flush();  
  139.                 str=str.substring(8);  
  140.             }  
  141.               
  142.             //最后不够8位添0  
  143.             int last1=8-str.length();  
  144.             for (int i = 0; i <last1; i++) {  
  145.                 str+="0";  
  146.             }  
  147.             s=str.substring(0, 8);  
  148. //          System.out.println(s);  
  149.             int d=changeStringToInt(s);  
  150.             fos.write(d);  
  151.               
  152.             //压缩后不够补0的个数暂  
  153.             fos.write(last1);  
  154.             fos.flush();  
  155.               
  156.             fos.close();  
  157.       
  158.     }  
  159.       
  160.     //插入元素位置的索引  
  161.     public int getIndex(HuffmNode node) {  
  162.         for (int i = 0; i < list.size(); i++) {  
  163.             if(node.getData()<=list.get(i).getData()){  
  164.                 return i;  
  165.             }  
  166.         }  
  167.        return list.size();  
  168.     }  
  169.       
  170.     //将字符串转换成整数  
  171.     public int changeStringToInt(String s){  
  172.         int v1=(s.charAt(0)-48)*128;  
  173.         int v2=(s.charAt(1)-48)*64;  
  174.         int v3=(s.charAt(2)-48)*32;  
  175.         int v4=(s.charAt(3)-48)*16;  
  176.         int v5=(s.charAt(4)-48)*8;  
  177.         int v6=(s.charAt(5)-48)*4;  
  178.         int v7=(s.charAt(6)-48)*2;  
  179.         int v8=(s.charAt(7)-48)*1;  
  180.         return v1+v2+v3+v4+v5+v6+v7+v8;  
  181.               
  182.     }  
  183. }  
重新测试了一个文件,Test也做了一下更改:
 
[java]  view plain  copy
 
  1. package com.huaxin.compress;  
  2.   
  3. public class Test {  
  4.     public static void main(String[] args) throws Exception {  
  5.         //创建压缩对象  
  6.         Compress compress = new Compress();  
  7.         //统计文件中0-255出现的次数  
  8.         compress.countTimes("C:\\Users\\Administrator\\Desktop\\my.docx");  
  9.         //构造哈夫曼树,并得到根节点  
  10.         HuffmNode root=compress.createTree();  
  11.         //得到哈夫曼编码  
  12.         compress.getHuffmCode(root, "");  
  13.         //压缩文件  
  14.         compress.compress("C:\\Users\\Administrator\\Desktop\\my.docx",  
  15.                 "C:\\Users\\Administrator\\Desktop\\my.docx.zip");  
  16.           
  17.     }  
  18.   
  19. }  
 
 
 
解压工程源代码:
[java]  view plain  copy
 
  1. package com.huaxin.decompress;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6.   
  7. public class Decompress {  
  8.       
  9.     //每个编码的长度  
  10.     public int [] codelengths = new int [256];  
  11.     //对应的哈夫曼编码值  
  12.     public String [] codeMap=new String[256];  
  13.       
  14.     public static void main(String[] args) {  
  15.           
  16.         Decompress d = new Decompress();  
  17.         d.decompress("C:\\Users\\Administrator\\Desktop\\my.docx.zip",  
  18.                 "C:\\Users\\Administrator\\Desktop\\mydecompress.docx");  
  19.       
  20.     }  
  21.       
  22.     /* 
  23.      * 解压思路: 
  24.      * 1、读取文件里面的码表 
  25.      * 2、得到码表 
  26.      * 3、读取数据 
  27.      * 4、还原数据 
  28.      */  
  29.       
  30.     public void decompress(String srcpath,String destpath) {  
  31.           
  32.         try {  
  33.             FileInputStream fis = new FileInputStream(srcpath);  
  34.             FileOutputStream fos = new FileOutputStream(destpath);  
  35.             int value;  
  36.             int codeLength=0;  
  37.             String code="";  
  38.             //还原码表  
  39.             for (int i = 0; i < codelengths.length; i++) {  
  40.                 value=fis.read();  
  41.                 codelengths[i]=value;  
  42. //              System.out.println(times[i]);  
  43.                 codeLength+=codelengths[i];  
  44.             }  
  45.               
  46.             //得到总长度  
  47.             //将总长度除以8的到字节个数  
  48.             int len=codeLength/8;  
  49.             //如果不是8的倍数,则字节个数加1(对应压缩补0的情况)  
  50.             if((codeLength)%8!=0){  
  51.                 len++;  
  52.             }  
  53.             //读取哈夫曼编码  
  54. //          System.out.println("codeLength:"+len);  
  55.             for (int i = 0; i < len; i++) {  
  56.                 //把读到的整数转换成二进制  
  57.                 code+=changeIntToString(fis.read());  
  58.                   
  59.             }  
  60. //          System.out.println("哈夫曼编码:"+code);  
  61.               
  62.             for (int i = 0; i < codeMap.length; i++) {  
  63.                 //如果第i个位置不为0 ,则说明第i个位置存储有哈夫曼编码  
  64.                 if(codelengths[i]!=0){  
  65.                     //将得到的一串哈夫曼编码按照长度分割分割  
  66.                     String ss=code.substring(0, codelengths[i]);  
  67.                     codeMap[i]=ss;  
  68.                     code=code.substring(codelengths[i]);  
  69.                 }else{  
  70.                     //为0则没有对应的哈夫曼编码  
  71.                     codeMap[i]="";  
  72.                 }  
  73.             }  
  74.               
  75.             //读取压缩的文件内容  
  76.             String codeContent="";  
  77.             while(fis.available()>1){  
  78.                 codeContent+=changeIntToString(fis.read());  
  79.             }  
  80.             //读取最后一个  
  81.             value=fis.read();  
  82.             //把最后补的0给去掉  
  83.             codeContent=codeContent.substring(0, codeContent.length()-value);  
  84.                   
  85.             for (int i = 0; i < codeContent.length(); i++) {  
  86.                   
  87.                 String codecontent=codeContent.substring(0, i+1);  
  88.                   
  89.                 for (int j = 0; j < codeMap.length; j++) {  
  90.                     if(codeMap[j].equals(codecontent)){  
  91. //                      System.out.println("截取的字符串:"+codecontent);  
  92.                         fos.write(j);  
  93.                         fos.flush();   
  94.                         codeContent=codeContent.substring(i+1);  
  95. //                      System.out.println("截取后剩余编码长度:"+codeContent.length());  
  96. //                      count=1;  
  97.                         i=-1;  
  98.                         break;  
  99.                     }  
  100.             }  
  101.             }  
  102. //          }  
  103.               
  104.             fos.close();  
  105.             fis.close();  
  106.               
  107.         } catch (Exception e) {  
  108.             e.printStackTrace();  
  109.         }  
  110.           
  111.   
  112.     }  
  113.       
  114.     //十进制转二进制字符串  
  115.     public String changeIntToString(int value) {  
  116.         String s="";  
  117.         for (int i = 0; i < 8; i++) {  
  118.             s=value%2+s;  
  119.             value=value/2;  
  120.         }  
  121.         return s;  
  122.     }  
  123.   
  124. }  

五、运行结果:字节大小相同
 
 
 
打开文件后文件内容相同
 
 
 
 
问题:为什么压缩后的文件反而更大了?
 
答:因为我们写了很多与该问价解压的内容进去;平时的压缩一般是针对大文件的;举个简单的例子,你用系统的压缩软件,压缩一个只要几个字节的文本,你会发现,压缩文件也变得比原文件更大了;
 
 
public class HuffmanCompress {

    // 压缩函数
    public void compress(File inputFile, File outputFile) {

        Compare cmp = new Compare();
        PriorityQueue<HufTree> queue = new PriorityQueue<HufTree>(12, cmp);

        // 映射字节及其对应的哈夫曼编码
        HashMap<Byte, String> map = new HashMap<Byte, String>();
        // 文件中含有的字符的种类数
        int i, char_kinds = 0;
        int char_temp, file_len = 0;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        // 哈夫曼树节点个数
        int node_num;
        HufTree[] huf_tree = null;
        String code_buf = null;

        // 临时存储字符频度的数组
        TmpNode[] tmp_nodes = new TmpNode[256];

        for (i = 0; i < 256; ++i) {
            tmp_nodes[i] = new TmpNode();
            tmp_nodes[i].weight = 0;
            tmp_nodes[i].uch = (byte) i;
        }

        try {
            
            fis = new FileInputStream(inputFile);
            fos = new FileOutputStream(outputFile);
            oos = new ObjectOutputStream(fos);
            // 统计字符频度,计算文件长度
            while ((char_temp = fis.read()) != -1) {
                ++tmp_nodes[char_temp].weight;
                ++file_len;
            }
            fis.close();
            Arrays.sort(tmp_nodes);
            // 排序后就会将频度为0的字节放在数组最后,从而去除频度为0的字节
            // 同时计算出字节的种类
            for (i = 0; i < 256; ++i) {
                if (tmp_nodes[i].weight == 0)
                    break;
            }
            char_kinds = i;

            // 只有一种字节的情况
            if (char_kinds == 1) {
                oos.writeInt(char_kinds);
                oos.writeByte(tmp_nodes[0].uch);
                oos.writeInt(tmp_nodes[0].weight);
                // 字节多于一种的情况
            } else {
                node_num = 2 * char_kinds - 1;// 计算哈夫曼树所有节点个数
                huf_tree = new HufTree[node_num];
                for (i = 0; i < char_kinds; ++i) {
                    huf_tree[i] = new HufTree();
                    huf_tree[i].uch = tmp_nodes[i].uch;
                    huf_tree[i].weight = tmp_nodes[i].weight;
                    huf_tree[i].parent = 0;

                    huf_tree[i].index = i;
                    queue.add(huf_tree[i]);
                }
                tmp_nodes = null;

                for (; i < node_num; ++i) {
                    huf_tree[i] = new HufTree();
                    huf_tree[i].parent = 0;
                }
                // 创建哈夫曼树
                createTree(huf_tree, char_kinds, node_num, queue);
                // 生成哈夫曼编码
                hufCode(huf_tree, char_kinds);
                // 写入字节种类
                oos.writeInt(char_kinds);
                for (i = 0; i < char_kinds; ++i) {
                    oos.writeByte(huf_tree[i].uch);
                    oos.writeInt(huf_tree[i].weight);

                    map.put(huf_tree[i].uch, huf_tree[i].code);
                }
                oos.writeInt(file_len);
                fis = new FileInputStream(inputFile);
                code_buf = "";
                // 将读出的字节对应的哈夫曼编码转化为二进制存入文件
                while ((char_temp = fis.read()) != -1) {

                    code_buf += map.get((byte) char_temp);

                    while (code_buf.length() >= 8) {
                        char_temp = 0;
                        for (i = 0; i < 8; ++i) {
                            char_temp <<= 1;
                            if (code_buf.charAt(i) == '1')
                                char_temp |= 1;
                        }
                        oos.writeByte((byte) char_temp);
                        code_buf = code_buf.substring(8);
                    }
                }
                // 最后编码长度不够8位的时候,用0补齐
                if (code_buf.length() > 0) {
                    char_temp = 0;
                    for (i = 0; i < code_buf.length(); ++i) {
                        char_temp <<= 1;
                        if (code_buf.charAt(i) == '1')
                            char_temp |= 1;
                    }
                    char_temp <<= (8 - code_buf.length());
                    oos.writeByte((byte) char_temp);
                }
            }
            oos.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 解压函数
    public void extract(File inputFile, File outputFile) {
        Compare cmp = new Compare();
        PriorityQueue<HufTree> queue = new PriorityQueue<HufTree>(12, cmp);

        int i;
        int file_len = 0;
        int writen_len = 0;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        ObjectInputStream ois = null;

        int char_kinds = 0;
        int node_num;
        HufTree[] huf_tree = null;
        byte code_temp;
        int root;
        try {
            fis = new FileInputStream(inputFile);
            ois = new ObjectInputStream(fis);
            fos = new FileOutputStream(outputFile);

            char_kinds = ois.readInt();

            // 字节只有一种的情况
            if (char_kinds == 1) {
                code_temp = ois.readByte();
                file_len = ois.readInt();
                while ((file_len--) != 0) {
                    fos.write(code_temp);
                }
                // 字节多于一种的情况
            } else {
                node_num = 2 * char_kinds - 1; // 计算哈夫曼树所有节点个数
                huf_tree = new HufTree[node_num];
                for (i = 0; i < char_kinds; ++i) {
                    huf_tree[i] = new HufTree();
                    huf_tree[i].uch = ois.readByte();
                    huf_tree[i].weight = ois.readInt();
                    huf_tree[i].parent = 0;

                    huf_tree[i].index = i;
                    queue.add(huf_tree[i]);
                }
                for (; i < node_num; ++i) {
                    huf_tree[i] = new HufTree();
                    huf_tree[i].parent = 0;
                }
                createTree(huf_tree, char_kinds, node_num, queue);

                file_len = ois.readInt();
                root = node_num - 1;
                while (true) {
                    code_temp = ois.readByte();
                    for (i = 0; i < 8; ++i) {
                        if ((code_temp & 128) == 128) {
                            root = huf_tree[root].rchild;
                        } else {
                            root = huf_tree[root].lchild;
                        }

                        if (root < char_kinds) {
                            fos.write(huf_tree[root].uch);
                            ++writen_len;
                            if (writen_len == file_len)
                                break;
                            root = node_num - 1; // 恢复为根节点的下标,匹配下一个字节
                        }
                        code_temp <<= 1;
                    }
                    // 在压缩的时候如果最后一个哈夫曼编码位数不足八位则补0
                    // 在解压的时候,补上的0之前的那些编码肯定是可以正常匹配到和他对应的字节
                    // 所以一旦匹配完补的0之前的那些编码,写入解压文件的文件长度就和压缩之前的文件长度是相等的
                    // 所以不需要计算补的0的个数
                    if (writen_len == file_len)
                        break;
                }
            }
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 构建哈夫曼树
    public void createTree(HufTree[] huf_tree, int char_kinds, int node_num, PriorityQueue<HufTree> queue) {
        int i;
        int[] arr = new int[2];
        for (i = char_kinds; i < node_num; ++i) {
            arr[0] = queue.poll().index;
            arr[1] = queue.poll().index;
            huf_tree[arr[0]].parent = huf_tree[arr[1]].parent = i;
            huf_tree[i].lchild = arr[0];
            huf_tree[i].rchild = arr[1];
            huf_tree[i].weight = huf_tree[arr[0]].weight + huf_tree[arr[1]].weight;

            huf_tree[i].index = i;
            queue.add(huf_tree[i]);
        }
    }

    // 获取哈夫曼编码
    public void hufCode(HufTree[] huf_tree, int char_kinds) {
        int i;
        int cur, next;

        for (i = 0; i < char_kinds; ++i) {
            String code_tmp = "";
            for (cur = i, next = huf_tree[i].parent; next != 0; cur = next, next = huf_tree[next].parent) {
                if (huf_tree[next].lchild == cur)
                    code_tmp += "0";
                else
                    code_tmp += "1";
            }
            huf_tree[i].code = (new StringBuilder(code_tmp)).reverse().toString();
        }
    }
}

 

 
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM