哈夫曼树算法压缩文件

来源:互联网 发布:荷塘淘宝论坛 编辑:程序博客网 时间:2024/05/16 01:05

今天上午上了哈夫曼算法压缩的课,我学习到了用哈夫曼算法压缩文件,可以将一个文件压缩百分之六十左右的大小。

具体原理是:文件是由一个个字节组成,而字节有自己的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;}

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






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



2 0
原创粉丝点击