哈夫曼编码译码器
1. 选择需要进行编码的文件
2.建立哈夫曼树
3.建立密码本并对文件编码
4.选择需要进行解码的文件并解码
5.按位压缩方式对文件进行压缩
6.解压压缩文件为编码文件
一共三个类,Huffman类也是程序的入口
下面的代码中注释将对代码有详细的讲解
public class Node<T> {
int key;
T charData;
Node leftChild;
Node rightChild;
}
public class Tree implements Comparable<Tree> {
private Node root;
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
public void inDisplay(Node node){
if (node!=null){
inDisplay(node.leftChild);
System.out.println(node.key+":"+node.charData);
inDisplay(node.rightChild);
}
}
@Override
public int compareTo(Tree o) {
return 0;
}
}
到这为止都没什么好说的,没涉及到什么算法,也没有复杂的操作,接下来是代码的核心(带注释)
package Misson6_bing;
import 实验3.KeyInput;
import java.awt.event.KeyEvent;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class Huffman {
private Map<Character,Integer> map=new HashMap<>();
private Map<Character,String> ce=new HashMap<>();
private PriorityQueue<Tree> trees=new PriorityQueue<>();
private String source;
public void init(String source){
this.source=source;
char[] chars= source.toCharArray();
for (char c :chars){
if (!map.containsKey(c)){
map.put(c,1);
}else {
map.put(c,map.get(c)+1);
}
}
afterInit();
}
private void afterInit() {
map.forEach((c,count)->{
Node<Character> node=new Node<>();
node.key=count;
node.charData=c;
Tree tree=new Tree();
tree.setRoot(node);
trees.add(tree);
});
}
public void build(){
while (this.trees.size()>1){
Tree left=this.trees.poll();
Tree right=this.trees.poll();
Node node=new Node();
node.key=left.getRoot().key+right.getRoot().key;
node.leftChild=left.getRoot();
node.rightChild=right.getRoot();
left.setRoot