当前位置:   article > 正文

用Java实现哈夫曼编码译码系统_哈夫曼编码系统

哈夫曼编码系统
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

class H{
    public static void main(String[] args) {
        //创建主窗口
        JFrame jf = new JFrame("哈夫曼编码译码系统");

        //设置一个容器
        JPanel jp = new JPanel();
        jp.setLayout(null);
        //创建按钮
        JButton jb1 = new JButton("字符");
        JButton jb2 = new JButton("文章");
        JButton jb3 = new JButton("翻译");
        //设置按钮并放入容器中
        jp.add(jb1);
        jb1.setBounds(80,100,200,30);
        jb1.setBackground(new Color(0x55FFA7));
        Font f = new Font("楷体_GB2312 Regular",Font.BOLD,20);
        jb1.setFont(f);
        jb1.setForeground(new Color(0xFF0000));
        jb1.setFocusPainted(false);

        //添加生成字符编码的鼠标点击事件
        jb1.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if(e.getButton() == MouseEvent.BUTTON1)
                {
                    Character_encoding();
                }
            }
            //字符编码窗口
            private void Character_encoding() {
                JFrame jf = new JFrame("字符编码");
                JPanel jp = new JPanel();
                jp.setLayout(null);
                //设置按钮
                JButton jb1 = new JButton("开始");
                jp.add(jb1);
                jb1.setBounds(100,10,200,30);
                jb1.setBackground(new Color(0xff5599));
                Font f = new Font("宋体_GB2312 Regular",Font.BOLD,20);
                jb1.setFont(f);
                jb1.setFocusPainted(false);


                JButton jb2 = new JButton("开始");
                jp.add(jb2);
                jb2.setBounds(130,250,100,30);
                jb2.setBackground(new Color(0xff5599));
                jb2.setFont(f);
                jb2.setFocusPainted(false);

                JButton jb3 = new JButton("保存");
                jp.add(jb3);
                jb3.setBounds(100,510,200,30);
                jb3.setFont(f);
                jb3.setFocusPainted(false);
                //设置文本框
                JTextArea jta1 = new JTextArea();
                jta1.setLineWrap(true);
                JScrollPane jsp1 = new JScrollPane(jta1);
                jp.add(jsp1);
                jsp1.setBounds(50,80,300,150);

                JTextArea jta2 = new JTextArea();
                jta1.setLineWrap(true);
                JScrollPane jsp2 = new JScrollPane(jta2);
                jp.add(jsp2);
                jsp2.setBounds(50,300,300,200);
                //导入文章
                jb1.addActionListener(e -> {
                    JFileChooser fileChooser = new JFileChooser();
                    int result = fileChooser.showOpenDialog(jf);
                    if (result == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();
                        try {
                            BufferedReader br = new BufferedReader(new FileReader(selectedFile));
                            String line;
                            while ((line = br.readLine()) != null) {
                                jta1.append(line + "\n");
                            }
                            br.close();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
                //文章编译
                jb2.addActionListener(e -> {
                    String str = jta1.getText(); // 获取jsp1中的文本内容
                    Map<Character, Integer> frequencyMap = calculateFrequencies(str);
                    TreeNode root = buildHuffmanTree(frequencyMap);
                    Map<Character, String> huffmanCodes = generateHuffmanCodes(root);
                    printHuffmanCodes(huffmanCodes,jta2);
                });
                //保存字符编码
                jb3.addActionListener(e -> {
                    try {
                        String content = jta2.getText();
                        FileWriter writer = new FileWriter("C:\\Users\\a1022\\Desktop\\字符.txt");
                        writer.write(content);
                        writer.close();
                        JOptionPane.showMessageDialog(jf, "保存成功");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(jf, "出错");
                    }
                });

                //把容器添加进窗口
                jf.add(jp);
                jf.setBounds(500, 300, 800, 800);
                jf.setVisible(true);
                jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                jf.setLocationRelativeTo(null);
            }
        });

        jp.add(jb2);
        jb2.setBounds(80,150+80,200,30);
        jb2.setBackground(new Color(0xFF9999));
        jb2.setFont(f);
        jb2.setForeground(new Color(0xFF0000));
        jb2.setFocusPainted(false);
        jb2.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if(e.getButton() == MouseEvent.BUTTON1)
                {
                    Article_coding();
                }
            }

            private void Article_coding() {
                JFrame jf = new JFrame("文章编码");
                JPanel jp = new JPanel();
                jp.setLayout(null);
                JButton jb1 = new JButton("打开文章");
                jp.add(jb1);
                jb1.setBounds(100,10,200,25);
                Font f = new Font("楷体_GB2312 Regular",Font.BOLD,20);
                jb1.setFont(f);
                jb1.setFocusPainted(false);

                JButton jb2 = new JButton("文章编码");
                jp.add(jb2);
                jb2.setBounds(300,300,200,25);
                jb2.setFont(f);
                jb2.setFocusPainted(false);

                JButton jb3 = new JButton("保存");
                jp.add(jb3);
                jb3.setBounds(300,530,200,25);
                jb3.setFont(f);
                jb3.setFocusPainted(false);

                JButton jb4 = new JButton("打开字符编码");
                jp.add(jb4);
                jb4.setBounds(500,10,200,25);
                jb4.setFont(f);
                jb4.setFocusPainted(false);

                //设置文本框
                JTextArea jta1 = new JTextArea();
                jta1.setLineWrap(true);
                JScrollPane jsp1 = new JScrollPane(jta1);
                jp.add(jsp1);
                jsp1.setBounds(50,80,300,150);

                JTextArea jta2 = new JTextArea();
                jta2.setLineWrap(true);
                JScrollPane jsp2 = new JScrollPane(jta2);
                jp.add(jsp2);
                jsp2.setBounds(450,80,300,150);

                JTextArea jta3 = new JTextArea();
                jta3.setLineWrap(true);
                JScrollPane jsp3 = new JScrollPane(jta3);
                jp.add(jsp3);
                jsp3.setBounds(50,360,700,150);
                //导入文章
                jb1.addActionListener(e -> {
                    JFileChooser fileChooser = new JFileChooser();
                    int result = fileChooser.showOpenDialog(jf);
                    if (result == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();
                        try {
                            BufferedReader br = new BufferedReader(new FileReader(selectedFile));
                            String line;
                            while ((line = br.readLine()) != null) {
                                jta1.append(line + "\n");
                            }
                            br.close();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
                //导入字符编码
                jb4.addActionListener(e -> {
                    JFileChooser fileChooser = new JFileChooser();
                    int result = fileChooser.showOpenDialog(jf);
                    if (result == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();
                        try {
                            BufferedReader br = new BufferedReader(new FileReader(selectedFile));
                            String line;
                            while ((line = br.readLine()) != null) {
                                jta2.append(line + "\n");
                            }
                            br.close();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
                //文章编译
                jb2.addActionListener(e -> {
                    String content = jta1.getText(); // 获取jsp1中的文本内容
                    String encoding = jta2.getText(); // 获取jsp2中的文本内容
                    //将字符编码存入哈希表中
                    Map<Character, String> huffmanMap = new HashMap<>();
                    String[] lines = encoding.split("\n");
                    for (String line : lines) {
//                        System.out.println(line);
                        String[] parts = line.split(":");
                        char character = parts[0].charAt(0);
                        String code = parts[1];
                        System.out.println(parts[0]+" "+parts[1]);
                        huffmanMap.put(character, code);
                    }
                    //进行编译
                    StringBuilder encodeString = new StringBuilder();
                    for(char c: content.toCharArray())
                    {
                        if(c != '\n')
                            encodeString.append(huffmanMap.get(c));
                    }
                    jta3.setText(encodeString.toString());
                });
                //保存文章编码
                jb3.addActionListener(e -> {
                    try {
                        String content = jta3.getText();
                        FileWriter writer = new FileWriter("C:\\Users\\a1022\\Desktop\\文章.txt");
                        writer.write(content);
                        writer.close();
                        JOptionPane.showMessageDialog(jf, "成功");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(jf, "出错");
                    }
                });
                //把容器添加进窗口
                jf.add(jp);
                jf.setBounds(400, 300, 800, 600);
                jf.setVisible(true);
                jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                jf.setLocationRelativeTo(null);
            }
        });

        jp.add(jb3);
        jb3.setBounds(80,200+80+80,200,30);
        jb3.setBackground(new Color(0xFF000));
        jb3.setFont(f);
        jb3.setForeground(new Color(0xFF));
        jb3.setFocusPainted(false);
        jb3.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if(e.getButton() == MouseEvent.BUTTON1)
                {
                    decoding();
                }
            }

            private void decoding() {
                JFrame jf = new JFrame("文本翻译");
                JPanel jp = new JPanel();
                jp.setLayout(null);
                JButton jb1 = new JButton("打开文章编码");
                jp.add(jb1);
                jb1.setBounds(100,10,200,25);
                Font f = new Font("楷体_GB2312 Regular",Font.BOLD,20);
                jb1.setFont(f);
                jb1.setFocusPainted(false);

                JButton jb2 = new JButton("翻译");
                jp.add(jb2);
                jb2.setBounds(300,300,200,25);
                jb2.setBackground(new Color(0xff5599));
                jb2.setFont(f);
                jb2.setFocusPainted(false);

                JButton jb3 = new JButton("保存");
                jp.add(jb3);
                jb3.setBounds(300,530,200,25);
                jb3.setFont(f);
                jb3.setFocusPainted(false);

                JButton jb4 = new JButton("打开字符编码");
                jp.add(jb4);
                jb4.setBounds(500,10,200,25);
                jb4.setFont(f);
                jb4.setFocusPainted(false);

                //设置文本框
                JTextArea jta1 = new JTextArea();
                jta1.setLineWrap(true);
                JScrollPane jsp1 = new JScrollPane(jta1);
                jp.add(jsp1);
                jsp1.setBounds(50,80,300,150);

                JTextArea jta2 = new JTextArea();
                jta2.setLineWrap(true);
                JScrollPane jsp2 = new JScrollPane(jta2);
                jp.add(jsp2);
                jsp2.setBounds(450,80,300,150);

                JTextArea jta3 = new JTextArea();
                jta3.setLineWrap(true);
                JScrollPane jsp3 = new JScrollPane(jta3);
                jp.add(jsp3);
                jsp3.setBounds(50,360,700,150);
                //导入文章编码
                jb1.addActionListener(e -> {
                    JFileChooser fileChooser = new JFileChooser();
                    int result = fileChooser.showOpenDialog(jf);
                    if (result == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();
                        try {
                            BufferedReader br = new BufferedReader(new FileReader(selectedFile));
                            String line;
                            while ((line = br.readLine()) != null) {
                                jta1.append(line + "\n");
                            }
                            br.close();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
                //导入字符编码
                jb4.addActionListener(e -> {
                    JFileChooser fileChooser = new JFileChooser();
                    int result = fileChooser.showOpenDialog(jf);
                    if (result == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();
                        try {
                            BufferedReader br = new BufferedReader(new FileReader(selectedFile));
                            String line;
                            while ((line = br.readLine()) != null) {
                                jta2.append(line + "\n");
                            }
                            br.close();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
                //文章编译
                jb2.addActionListener(e -> {
                    String content = jta1.getText(); // 获取jsp1中的文本内容
                    String encoding = jta2.getText(); // 获取jsp1中的文本内容
                    Map<String, Character> huffmanMap = new HashMap<>();
                    String[] lines = encoding.split("\n");

                    for (String line : lines) {
                        String[] parts = line.split(":");
                        Character character = parts[0].charAt(0);
                        String key = parts[1];
                        huffmanMap.put(key, character);
                    }

                    StringBuilder encodeString = new StringBuilder();
                    int L = 0,R = 1;
                    while(R <= content.length()) {
                        String part = content.substring(L,R);
                        if(huffmanMap.containsKey(part)) {
                            encodeString.append(huffmanMap.get(part));
                            L = R;
                        }
                        R++;
                    }
                    jta3.setText(encodeString.toString()); // 将文本内容设置到jsp2中

                });
                //保存文章
                jb3.addActionListener(e -> {
                    try {
                        String content = jta2.getText();
                        FileWriter writer = new FileWriter("F:\\MyData\\Desktop\\decoding.txt");
                        writer.write(content);
                        writer.close();
                        JOptionPane.showMessageDialog(jf, "成功");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(jf, "出错");
                    }
                });
                //把容器添加进窗口
                jf.add(jp);
                jf.setBounds(400, 300, 800, 600);
                jf.setVisible(true);
                jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                jf.setLocationRelativeTo(null);
            }
        });

        //把容器添加进主窗口,窗口大小
        jf.add(jp);
        jf.setBounds(400, 300, 400, 600);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setLocationRelativeTo(null);


    }
    private static Map<Character, String> parseMappingString(String S) {
        Map<Character, String> huffmanMap = new HashMap<>();
        String[] lines = S.split("\n");

        for (String line : lines) {
            String[] parts = line.split(":");
            char character = parts[0].charAt(0);
            String code = parts[1];
            huffmanMap.put(character, code);
        }

        return huffmanMap;
    }
    //计算频率
    public static Map<Character, Integer> calculateFrequencies(String str) {
        Map<Character, Integer> frequencyMap = new HashMap<>();

        for (char ch : str.toCharArray()) {
            if(ch=='\n') continue;
            frequencyMap.put(ch, frequencyMap.getOrDefault(ch, 0) + 1);
        }

        return frequencyMap;
    }
    //根据哈希表建树
    public static TreeNode buildHuffmanTree(Map<Character, Integer> frequencyMap) {
        PriorityQueue<TreeNode> pq = new PriorityQueue<>(new HuffmanComparator());

        for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
            char ch = entry.getKey();
            int freq = entry.getValue();
            TreeNode node = new TreeNode(ch, freq);
            pq.offer(node);
        }

        while (pq.size() > 1) {
            TreeNode leftChild = pq.poll();
            TreeNode rightChild = pq.poll();
            int sum = leftChild.freq + rightChild.freq;

            TreeNode parent = new TreeNode('\0', sum);
            parent.left = leftChild;
            parent.right = rightChild;

            pq.offer(parent);
        }

        return pq.poll();
    }
    //生成哈夫曼编码
    public static Map<Character, String> generateHuffmanCodes(TreeNode root) {
        Map<Character, String> huffmanCodes = new HashMap<>();
        generateCodes(root, "", huffmanCodes);
        return huffmanCodes;
    }
    //生成哈夫曼编码
    public static void generateCodes(TreeNode node, String code, Map<Character, String> huffmanCodes) {
        if (node == null) {
            return;
        }

        if (node.left == null && node.right == null) {
            huffmanCodes.put(node.ch, code);
            return;
        }

        generateCodes(node.left, code + "0", huffmanCodes);
        generateCodes(node.right, code + "1", huffmanCodes);
    }
    //打印哈夫曼编码
    public static void printHuffmanCodes(Map<Character, String> huffmanCodes, JTextArea jta2) {
        String content = "";
        for (Map.Entry<Character, String> entry : huffmanCodes.entrySet()) {
            char ch = entry.getKey();
            String code = entry.getValue();
            content += ch + ":" + code + "\n";
            jta2.setText(content);
        }
    }
}

class TreeNode {
    char ch;
    int freq;
    TreeNode left;
    TreeNode right;

    public TreeNode(char ch, int freq) {
        this.ch = ch;
        this.freq = freq;
    }
}

class HuffmanComparator implements Comparator<TreeNode> {
    public int compare(TreeNode node1, TreeNode node2) {
        return node1.freq - node2.freq;
    }
}


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/859215
推荐阅读
相关标签
  

闽ICP备14008679号