您的位置:首页 > 其它

哈夫曼树算法压缩文件

2016-03-12 15:22 477 查看
今天上午上了哈夫曼算法压缩的课,我学习到了用哈夫曼算法压缩文件,可以将一个文件压缩百分之六十左右的大小。

具体原理是:文件是由一个个字节组成,而字节有自己的ASCII码值,然后用一个整形数组把文件的ASCII码值记下来,出现了一个就在其对应的ASCII值得int数组下标加一。然后用哈夫曼算法处理这个整形数组,得到哈夫曼编码值,然后读入文件的哈夫曼编码值,最后写入压缩文件。

哈夫曼压缩需要三个容器,一个是存数据字节,一个是哈夫曼节点,一个是存哈夫曼编码

代码如下:

private int[] data = new int[256];
private LinkedList<HuffmNode> list = new LinkedList<HuffmNode>();
private String[] codestr = new String[256];
//代码块:让哈夫曼编码置为空字符串
{
for(int i=0;i<codestr.length;i++){
codestr[i] = "";
}
}


压缩文件分五个步骤执行:

public static void main(String[] args) {
Compress com = new Compress();
//1.读取源文件,统计每个字节出现次数
com.datatime();
//2.构建哈夫曼节点
com.creatNode();
//3.构建哈夫曼树
com.creatHuffmTree();
//4.得到哈夫曼编码
com.getCode(com.list.get(0),"");
//5.再次读入文件的哈夫曼编码,并写入压缩文件(保存数据顺序,用于解压);
com.writeFile();
}


具体方法代码如下:

public void datatime(){
try {
//文件输入流读取test.txt文件
FileInputStream fis = new FileInputStream("C:\\Users\\asus\\Desktop\\test.txt");
int value = fis.read();
while(value!=-1){
data[value] ++;
value = fis.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}


创建节点、哈夫曼树和构造哈夫曼编码和上一个博客一样,略。

<span style="font-size:24px;">//压缩文件的实现
public void writeFile(){
//1.读文件,得到编码串
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\asus\\Desktop\\test.zip");
FileInputStream fis = new FileInputStream("C:\\Users\\asus\\Desktop\\test.txt");
int value = fis.read();
String str = "";
while(value!=-1){
String c = codestr[value];
str = str + c ;
value = fis.read();
}
//2.压缩结果写入压缩文件
while(str.length()>=8){
String s = str.substring(0,8);
int v = StringToInt(s);
fos.write(v);
fos.flush();
str = str.substring(8);	//截取从第八位字节后面的字节数
}
//3.把最后一点字节写出去
int zero = 8 - str.length();
for(int i=0;i<zero;i++){
str = str + "0";
}
int v = StringToInt(str);
fos.write(v);
fos.flush();
//4.把补零个数写入文件
fos.write(zero);
fos.flush();
fis.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}</span>
这里涉及到了八位字符串转成int型的方法:

public int StringToInt(String s){
int c1 = (int)s.charAt(0)-48;
int c2 = (int)s.charAt(1)-48;
int c3 = (int)s.charAt(2)-48;
int c4 = (int)s.charAt(3)-48;
int c5 = (int)s.charAt(4)-48;
int c6 = (int)s.charAt(5)-48;
int c7 = (int)s.charAt(6)-48;
int c8 = (int)s.charAt(7)-48;
int result = c8*1+c7*2+c6*4+c5*8+c4*16+c3*32+c2*64+c1*128;
return result;
}


下面是程序操作的结果(图):









这就是今天所学到的哈夫曼压缩,明天就学习哈夫曼解压了,加油!




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: