数据结构 [Java版本] 树之应用 哈夫曼编码之文件压缩

哈夫曼编码 最佳实践-文件压缩

我们学习了通过赫夫曼编码对一个字符串进行编码和解码, 下面我们来完成对文件的压缩和解压, 具体要求:给你一个图片文件,要求对其进行无损压缩, 看看压缩效果如何。
思路:读取文件-> 得到赫夫曼编码表 -> 完成压缩

代码实现:

public class HuffmanCode {
    public static void main(String[] args) {
        //测试压缩文件  G:\360downloads\1001540.jpg

        String srcFile = "G:\\360downloads\\1001540.jpg";
        String destFile = "G:\\360downloads\\1001540Copy.zip";
        //压缩操作
        zipFile(srcFile, destFile);

        //解压操作
        String srcFileSrc = "G:\\360downloads\\1001540Copy.zip";
        String destFileSrc = "G:\\360downloads\\1001540CopyToJPG.jpg";
        unZipFile(srcFileSrc,destFileSrc);
    }

    /**
     * 数据压缩
     *
     * @param srcPath  传入完整的路径
     * @param destPath 输出;路径
     */
    public static void zipFile(String srcPath, String destPath) {
        //创建输出流

        //创建输入流
        FileInputStream is = null;
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            is = new FileInputStream(srcPath);
            byte[] bytes = new byte[is.available()];
            //读取文件
            is.read(bytes);
            //直接对文件进行压缩
            byte[] huffmanZipBytes = huffmanZip(bytes);
            //输出
            fos = new FileOutputStream(destPath);
            //创建一个
            oos = new ObjectOutputStream(fos);
            //以对象流的方式写入 赫夫曼编码 为了回复数据流使用
            oos.writeObject(huffmanZipBytes);
            //把赫夫曼编码放进去
            oos.writeObject(huffmanCodes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                fos.close();
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

测试

压缩

哈夫曼编码 最佳实践-文件解压(文件恢复)

具体要求:将前面压缩的文件,重新恢复成原来的文件。
思路:读取压缩文件(数据和赫夫曼编码表)-> 完成解压(文件恢复)

代码实现:
代码实现:

public class HuffmanCode {
    public static void main(String[] args) {
        //测试压缩文件  G:\360downloads\1001540.jpg

        String srcFile = "G:\\360downloads\\1001540.jpg";
        String destFile = "G:\\360downloads\\1001540Copy.zip";
        //压缩操作
        zipFile(srcFile, destFile);

        //解压操作
        String srcFileSrc = "G:\\360downloads\\1001540Copy.zip";
        String destFileSrc = "G:\\360downloads\\1001540CopyToJPG.jpg";
        unZipFile(srcFileSrc,destFileSrc);
    }

    /**
     * 数据解压
     *
     * @param zipFileSrc 传入完整的路径
     * @param destPath   输出;路径
     */
    public static void unZipFile(String zipFileSrc, String destPath) {
        //定义文件输入流
        InputStream is = null;
        //定义一个对象输入了
        ObjectInputStream ois = null;
        //定义文件输出
        OutputStream os = null;
        try {
            is = new FileInputStream(zipFileSrc);
            ois = new ObjectInputStream(is);
            //读取 数组
            byte[] bytes = (byte[]) ois.readObject();
            //读取编码表
            Map<Byte, String> byteStringMap = (Map<Byte, String>) ois.readObject();
            //节码
            byte[] decode = decode(byteStringMap, bytes);
            os = new FileOutputStream(destPath);
            //写出数据到
            os.write(decode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
                ois.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

测试

测试

完整代码

package cn.icanci.datastructure.haffmantree.haffmancode;

import java.io.ObjectOutputStream;

import java.io.FileOutputStream;

import java.io.*;

import java.io.FileInputStream;
import java.util.*;

/**
 * @Author: icanci
 * @ProjectName: AlgorithmAndDataStructure
 * @PackageName: cn.icanci.datastructure.haffmantree.haffmancode
 * @Date: Created in 2020/3/15 21:04
 * @ClassAction: 哈夫曼编码
 */
public class HuffmanCode {
    public static void main(String[] args) {
        //测试压缩文件  G:\360downloads\1001540.jpg

        String srcFile = "G:\\360downloads\\1001540.jpg";
        String destFile = "G:\\360downloads\\1001540Copy.zip";
        //压缩操作
        zipFile(srcFile, destFile);

        //解压操作
        String srcFileSrc = "G:\\360downloads\\1001540Copy.zip";
        String destFileSrc = "G:\\360downloads\\1001540CopyToJPG.jpg";
        unZipFile(srcFileSrc,destFileSrc);
    }

    /**
     * 数据解压
     *
     * @param zipFileSrc 传入完整的路径
     * @param destPath   输出;路径
     */
    public static void unZipFile(String zipFileSrc, String destPath) {
        //定义文件输入流
        InputStream is = null;
        //定义一个对象输入了
        ObjectInputStream ois = null;
        //定义文件输出
        OutputStream os = null;
        try {
            is = new FileInputStream(zipFileSrc);
            ois = new ObjectInputStream(is);
            //读取 数组
            byte[] bytes = (byte[]) ois.readObject();
            //读取编码表
            Map<Byte, String> byteStringMap = (Map<Byte, String>) ois.readObject();
            //节码
            byte[] decode = decode(byteStringMap, bytes);
            os = new FileOutputStream(destPath);
            //写出数据到
            os.write(decode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
                ois.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 数据压缩
     *
     * @param srcPath  传入完整的路径
     * @param destPath 输出;路径
     */
    public static void zipFile(String srcPath, String destPath) {
        //创建输出流

        //创建输入流
        FileInputStream is = null;
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            is = new FileInputStream(srcPath);
            byte[] bytes = new byte[is.available()];
            //读取文件
            is.read(bytes);
            //直接对文件进行压缩
            byte[] huffmanZipBytes = huffmanZip(bytes);
            //输出
            fos = new FileOutputStream(destPath);
            //创建一个
            oos = new ObjectOutputStream(fos);
            //以对象流的方式写入 赫夫曼编码 为了回复数据流使用
            oos.writeObject(huffmanZipBytes);
            //把赫夫曼编码放进去
            oos.writeObject(huffmanCodes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                fos.close();
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 数据解码
     *
     * @param huffmanCodes 编码表
     * @param bytes        赫夫曼编码得到的字节数组
     * @return
     */
    private static byte[] decode(Map<Byte, String> huffmanCodes, byte[] bytes) {
        //1.先得到 bytes 对应的二进制字符串
        StringBuilder stringBuilder = new StringBuilder();
        //2.将byte数组
        for (int i = 0; i < bytes.length; i++) {
            boolean flag = (i == bytes.length - 1);
            stringBuilder.append(byteToString(!flag, bytes[i]));
        }

        //把字符串按照指定的赫夫曼编码进行节码
        //把赫夫曼编码进行调换 反响查询
        Map<String, Byte> map = new HashMap<String, Byte>();
        for (Map.Entry<Byte, String> entry : huffmanCodes.entrySet()) {
            map.put(entry.getValue(), entry.getKey());
        }
        //创建一个集合
        ArrayList<Byte> list = new ArrayList<>();
        for (int i = 0; i < stringBuilder.length(); ) {
            int count = 1;
            boolean flag = true;
            Byte b = null;
            while (flag) {
                //取出一个 1 0
                String key = stringBuilder.substring(i, i + count);
                b = map.get(key);
                if (b == null) {
                    count++;
                } else {
                    flag = false;
                }
            }
            list.add(b);
            i += count;
        }
        //把list数组放在 byte数组中
        byte[] by = new byte[list.size()];
        for (int i = 0; i < list.size(); i++) {
            by[i] = list.get(i);
        }
        return by;
    }

    //数据的解压
    //重新转成字符串  然后在转为 二进制字符串

    private static String byteToString(boolean flag, byte b) {
        int temp = b;
        //如何是证数 需要补位
        //按位与
        if (flag) {
            temp |= 256;
        }
        //返回的是temp 的对应的补码
        String string = Integer.toBinaryString(temp);
        if (flag) {
            return string.substring(string.length() - 8);
        } else {
            return string;
        }
    }


    /**
     * @param bytes 需要压缩的
     * @return 压缩之后的
     */
    private static byte[] huffmanZip(byte[] bytes) {
        List<Node> nodes = getNodes(bytes);
        Node huffmanTree = createHuffmanTree(nodes);
        preOrder(huffmanTree);
        getCodes(huffmanTree);
        byte[] zip = zip(bytes, huffmanCodes);
        return zip;
    }


    /**
     * 编写一个方法 将字符串对应的Byte数组 通过生成的哈夫曼编码表
     *
     * @param bytes
     * @param huffmanCodes
     * @return 对应的 byte数组
     */
    private static byte[] zip(byte[] bytes, Map<Byte, String> huffmanCodes) {
        //先利用 huffmanCodes 将 bytes 转成 哈夫曼编码对应的字符串
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b : bytes) {
            stringBuilder.append(huffmanCodes.get(b));
        }
        //将字符串转成 byte数组
        //统计返回的 长度
        int len;
        if (stringBuilder.length() % 8 == 0) {
            len = stringBuilder.length() / 8;
        } else {
            len = stringBuilder.length() / 8 + 1;
        }
        //创建存储压缩后的数组
        byte[] by = new byte[len];
        int index = 0;
        for (int i = 0; i < stringBuilder.length(); i += 8) {
            String strByte;
            if (i + 8 > stringBuilder.length()) {
                //不够8位
                strByte = stringBuilder.substring(i);
            } else {
                strByte = stringBuilder.substring(i, i + 8);
            }
            by[index] = (byte) Integer.parseInt(strByte, 2);
            index++;
        }
        return by;
    }


    //生成赫夫曼树的对应的赫夫曼编码
    //思路分析:
    //1.将赫夫曼编码存放着在 Map<Byte,String>
    //2.在生成哈夫曼编码表的时候 需要去拼接路径

    static Map<Byte, String> huffmanCodes = new HashMap<Byte, String>();
    static StringBuilder sb = new StringBuilder();


    private static void getCodes(Node root) {
        if (root == null) {
            System.out.println("空");
        } else {
            getCodes(root, "", sb);
        }
    }


    /**
     * 功能:将传入的node节点的所有叶子节点的赫夫曼编码得到 并放入huffmanCodes集合
     *
     * @param node          传入节点
     * @param code          传入;路径 左 0 右1
     * @param stringbuilder 拼接路径的
     */
    private static void getCodes(Node node, String code, StringBuilder stringbuilder) {
        StringBuilder stringBuilder = new StringBuilder(stringbuilder);
        stringBuilder.append(code);
        if (node != null) {
            //判断当前Node是叶子节点还是非叶子节点
            if (node.data == null) {
                getCodes(node.left, "0", stringBuilder);
                getCodes(node.right, "1", stringBuilder);
            } else {
                //是叶子节点 找到了叶子节点的最后
                huffmanCodes.put(node.data, stringBuilder.toString());
            }
        }
    }


    //前序遍历
    private static void preOrder(Node root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("空");
        }
    }

    /**
     * 接收字节数组
     *
     * @param bytes 需要转换的字节数组
     * @return 返回
     */
    private static List<Node> getNodes(byte[] bytes) {
        //创建一个ArrayList
        List<Node> nodes = new ArrayList<>();
        //编译bytes 统计
        HashMap<Byte, Integer> hashMap = new HashMap<>();
        for (byte b : bytes) {
            Integer count = hashMap.get(b);
            if (count == null) {
                hashMap.put(b, 1);
            } else {
                hashMap.put(b, count + 1);
            }
        }
        //把每个键值对 转成一个Node对象
        for (Map.Entry<Byte, Integer> entry : hashMap.entrySet()) {
            nodes.add(new Node(entry.getKey(), entry.getValue()));
        }
        return nodes;
    }

    private static Node createHuffmanTree(List<Node> nodes) {
        while (nodes.size() > 1) {
            Collections.sort(nodes);
            Node left = nodes.get(0);
            Node right = nodes.get(1);
            //创建一个新的二叉树 没有根节点 只有权值
            Node parent = new Node(null, left.weight + right.weight);
            parent.left = left;
            parent.right = right;
            nodes.remove(left);
            nodes.remove(right);
            nodes.add(parent);
        }
        return nodes.get(0);
    }
}

//创建Node

class Node implements Comparable<Node> {
    //存放数据本身
    Byte data;
    //权值
    int weight;
    Node left;
    Node right;

    public Node(Byte data, int weight) {
        this.data = data;
        this.weight = weight;
    }

    @Override
    public int compareTo(Node o) {
        //从小到大
        return this.weight - o.weight;
    }

    @Override
    public String toString() {
        return "Node{" +
                "data=" + data +
                ", weight=" + weight +
                '}';
    }

    //前序遍历
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }
}
赫夫曼编码压缩文件注意事项

如果文件本身就是经过压缩处理的,那么使用赫夫曼编码再压缩效率不会有明显变化, 比如视频,ppt 等等文件 [举例压一个 .ppt]
赫夫曼编码是按字节来处理的,因此可以处理所有的文件(二进制文件、文本文件) [举例压一个.xml文件]
如果一个文件中的内容,重复的数据不多,压缩效果也不会很明显.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容