本篇博文将介绍什么是哈夫曼树,并且如何在java语言中构建一棵哈夫曼树,怎么利用哈夫曼树实现对文件的压缩和解压。首先,先来了解下什么哈夫曼树。

一、哈夫曼树

哈夫曼树属于二叉树,即树的结点最多拥有2个孩子结点。若该二叉树带权路径长度达到最小,称这样的二叉树为最优二叉树,也称为哈夫曼树(Huffman Tree)。哈夫曼树是带权路径长度最短的树,权值较大的结点离根较近。

(一)树的相关概念

1.路径和路径长度

在一棵树中,从一个结点往下可以达到的孩子或孙子结点之间的通路,称为路径。通路中分支的数目称为路径长度。若规定根结点的层数为1,则从跟结点到第L层结点的路径长度为L-1。

2.结点的权和带权路径长度

若将树中结点赋给一个有着某种含义的数值,则这个数值称为该结点的权。结点的带权路径长度为:从根结点到该结点之间的路径长度与该结点的权的乘积。

3.树的带权路径长度

树的带权路径长度规定为所有叶子结点的带权路径长度之和,记为WPL。

(二)哈夫曼树的构造原理

假设有n个权值,则构造出的哈夫曼树有n个叶子结点。 n个权值分别设为 w1、w2、…、wn,则哈夫曼树的构造规则为:

(1) 将w1、w2、…,wn看成是有n 棵树的森林(每棵树仅有一个结点);

(2) 在森林中选出两个根结点的权值最小的树合并,作为一棵新树的左、右子树,且新树的根结点权值为其左、右子树根结点权值之和;

(3)从森林中删除选取的两棵树,并将新树加入森林;

(4)重复(2)、(3)步,直到森林中只剩一棵树为止,该树即为所求得的哈夫曼树。

(三)哈夫曼编码

在数据通信中,需要将传送的文字转换成二进制的字符串,用0,1码的不同排列来表示字符。例如,需传送的报文为“AFTER DATA EAR ARE ART AREA”,这里用到的字符集为“A,E,R,T,F,D”,各字母出现的次数为{8,4,5,3,1,1}。现要求为这些字母设计编码。要区别6个字母,最简单的二进制编码方式是等长编码,固定采用3位二进制,可分别用000、001、010、011、100、101对“A,E,R,T,F,D”进行编码发送,当对方接收报文时再按照三位一分进行译码。显然编码的长度取决报文中不同字符的个数。若报文中可能出现26个不同字符,则固定编码长度为5。然而,传送报文时总是希望总长度尽可能短。在实际应用中,各个字符的出现频度或使用次数是不相同的,如A、B、C的使用频率远远高于X、Y、Z,自然会想到设计编码时,让使用频率高的用短编码,使用频率低的用长编码,以优化整个报文编码。

为使不等长编码为前缀编码(即要求一个字符的编码不能是另一个字符编码的前缀),可用字符集中的每个字符作为叶子结点生成一棵编码二叉树,为了获得传送报文的最短长度,可将每个字符的出现频率作为字符结点的权值赋予该结点上,显然字使用频率越小权值越小,权值越小叶子就越靠下,于是频率小编码长,频率高编码短,这样就保证了此树的最小带权路径长度效果上就是传送报文的最短长度。因此,求传送报文的最短长度问题转化为求由字符集中的所有字符作为叶子结点,由字符出现频率作为其权值所产生的哈夫曼树的问题。利用哈夫曼树来设计二进制的前缀编码,既满足前缀编码的条件,又保证报文编码总长最短。

二、用Java实现哈夫曼树结构

(一)创建树的结点结构

首先要搞清楚,我们用哈夫曼树实现压缩的原理是要先统计好被压缩文件的每个字节的次数,以这个次数为依据来构建哈夫曼树,使得出现次数多字节对应的哈夫曼编码要短,而出现次数少的字节对应的哈夫曼编码要长一些,所以树结点结构中的要保存的数据就有文件中的字节(用byte类型),字节出现的次数(用int类型),表示是左孩子还是右孩子的数据,指向左孩子和右孩子的两个结点结构对象。同时,如果希望能够直接比较结点中的字节出现次数,可以重写一个比较方法。

  1. /**
  2. * 二叉树结点元素结构
  3. *
  4. * @author Bill56
  5. *
  6. */
  7. public class Node implements Comparable<Node> {
  8. // 元素内容
  9. public int number;
  10. // 元素次数对应的字节
  11. public byte by;
  12. // 表示结点是左结点还是右结点,0表示左,1表示右
  13. public String type = "";
  14. // 指向该结点的左孩子
  15. public Node leftChild;
  16. // 指向该结点的右孩子
  17. public Node rightChild;
  18. /**
  19. * 构造方法,需要将结点的值传入
  20. *
  21. * @param number
  22. *            结点元素的值
  23. */
  24. public Node(int number) {
  25. this.number = number;
  26. }
  27. /**
  28. * 构造方法
  29. *
  30. * @param by
  31. *            结点元素字节值
  32. * @param number
  33. *            结点元素的字节出现次数
  34. *
  35. */
  36. public Node(byte by, int number) {
  37. super();
  38. this.by = by;
  39. this.number = number;
  40. }
  41. @Override
  42. public int compareTo(Node o) {
  43. // TODO Auto-generated method stub
  44. return this.number - o.number;
  45. }
  46. }
/**
* 二叉树结点元素结构
*
* @author Bill56
*
*/
public class Node implements Comparable<Node> { // 元素内容
public int number;
// 元素次数对应的字节
public byte by;
// 表示结点是左结点还是右结点,0表示左,1表示右
public String type = "";
// 指向该结点的左孩子
public Node leftChild;
// 指向该结点的右孩子
public Node rightChild; /**
* 构造方法,需要将结点的值传入
*
* @param number
* 结点元素的值
*/
public Node(int number) {
this.number = number;
} /**
* 构造方法
*
* @param by
* 结点元素字节值
* @param number
* 结点元素的字节出现次数
*
*/
public Node(byte by, int number) {
super();
this.by = by;
this.number = number;
} @Override
public int compareTo(Node o) {
// TODO Auto-generated method stub
return this.number - o.number;
} }

 (二)创建树结构类

树结构中主要包含一些列对结点对象的操作,如,通过一个队列生成一个map对象(用来存放字节对应的次数),通过队列生成一棵树,通过树的根结点对象生成一个哈夫曼map,获得哈夫曼编码等。

  1. /**
  2. * 由结点元素构成的二叉树树结构,由结点作为树的根节点
  3. *
  4. * @author Bill56
  5. *
  6. */
  7. public class Tree {
  8. /**
  9. * 根据map生成一个由Node组成的优先队列
  10. *
  11. * @param map
  12. *            需要生成队列的map对象
  13. * @return 优先队列对象
  14. */
  15. public PriorityQueue<Node> map2Queue(HashMap<Byte, Integer> map) {
  16. // 创建队列对象
  17. PriorityQueue<Node> queue = new PriorityQueue<Node>();
  18. if (map != null) {
  19. // 获取map的key
  20. Set<Byte> set = map.keySet();
  21. for (Byte b : set) {
  22. // 将获取到的key中的值连同key一起保存到node结点中
  23. Node node = new Node(b, map.get(b));
  24. // 写入到优先队列
  25. queue.add(node);
  26. }
  27. }
  28. return queue;
  29. }
  30. /**
  31. * 根据优先队列创建一颗哈夫曼树
  32. *
  33. * @param queue
  34. *            优先队列
  35. * @return 哈夫曼树的根结点
  36. */
  37. public Node queue2Tree(PriorityQueue<Node> queue) {
  38. // 当优先队列元素大于1的时候,取出最小的两个元素之和相加后再放回到优先队列,留下的最后一个元素便是根结点
  39. while (queue.size() > 1) {
  40. // poll方法获取并移除此队列的头,如果此队列为空,则返回 null
  41. // 取出最小的元素
  42. Node n1 = queue.poll();
  43. // 取出第二小的元素
  44. Node n2 = queue.poll();
  45. // 将两个元素的字节次数值相加构成新的结点
  46. Node newNode = new Node(n1.number + n2.number);
  47. // 将新结点的左孩子指向最小的,而右孩子指向第二小的
  48. newNode.leftChild = n1;
  49. newNode.rightChild = n2;
  50. n1.type = "0";
  51. n2.type = "1";
  52. // 将新结点再放回队列
  53. queue.add(newNode);
  54. }
  55. // 优先队列中留下的最后一个元素便是根结点,将其取出返回
  56. return queue.poll();
  57. }
  58. /**
  59. * 根据传入的结点遍历树
  60. *
  61. * @param node
  62. *            遍历的起始结点
  63. */
  64. public void ergodicTree(Node node) {
  65. if (node != null) {
  66. System.out.println(node.number);
  67. // 递归遍历左孩子的次数
  68. ergodicTree(node.leftChild);
  69. // 递归遍历右孩子的次数
  70. ergodicTree(node.rightChild);
  71. }
  72. }
  73. /**
  74. * 根据哈夫曼树生成对应叶子结点的哈夫曼编码
  75. *
  76. * @param root
  77. *            树的根结点
  78. * @return 保存叶子结点的哈夫曼map
  79. */
  80. public HashMap<Byte, String> tree2HfmMap(Node root) {
  81. HashMap<Byte, String> hfmMap = new HashMap<>();
  82. getHufmanCode(root, "", hfmMap);
  83. return hfmMap;
  84. }
  85. /**
  86. * 根据输入的结点获得哈夫曼编码
  87. *
  88. * @param node
  89. *            遍历的起始结点
  90. * @param code
  91. *            传入结点的编码类型
  92. * @param hfmMap
  93. *            用来保存字节对应的哈夫曼编码的map
  94. */
  95. private void getHufmanCode(Node node, String code, HashMap<Byte, String> hfmMap) {
  96. if (node != null) {
  97. code += node.type;
  98. // 当node为叶子结点的时候
  99. if (node.leftChild == null && node.rightChild == null) {
  100. hfmMap.put(node.by, code);
  101. }
  102. // 递归遍历左孩子的次数
  103. getHufmanCode(node.leftChild, code, hfmMap);
  104. // 递归遍历右孩子的次数
  105. getHufmanCode(node.rightChild, code, hfmMap);
  106. }
  107. }
  108. }
/**
* 由结点元素构成的二叉树树结构,由结点作为树的根节点
*
* @author Bill56
*
*/
public class Tree { /**
* 根据map生成一个由Node组成的优先队列
*
* @param map
* 需要生成队列的map对象
* @return 优先队列对象
*/
public PriorityQueue<Node> map2Queue(HashMap<Byte, Integer> map) {
// 创建队列对象
PriorityQueue<Node> queue = new PriorityQueue<Node>();
if (map != null) {
// 获取map的key
Set<Byte> set = map.keySet();
for (Byte b : set) {
// 将获取到的key中的值连同key一起保存到node结点中
Node node = new Node(b, map.get(b));
// 写入到优先队列
queue.add(node);
}
}
return queue;
} /**
* 根据优先队列创建一颗哈夫曼树
*
* @param queue
* 优先队列
* @return 哈夫曼树的根结点
*/
public Node queue2Tree(PriorityQueue<Node> queue) {
// 当优先队列元素大于1的时候,取出最小的两个元素之和相加后再放回到优先队列,留下的最后一个元素便是根结点
while (queue.size() > 1) {
// poll方法获取并移除此队列的头,如果此队列为空,则返回 null
// 取出最小的元素
Node n1 = queue.poll();
// 取出第二小的元素
Node n2 = queue.poll();
// 将两个元素的字节次数值相加构成新的结点
Node newNode = new Node(n1.number + n2.number);
// 将新结点的左孩子指向最小的,而右孩子指向第二小的
newNode.leftChild = n1;
newNode.rightChild = n2;
n1.type = "0";
n2.type = "1";
// 将新结点再放回队列
queue.add(newNode);
}
// 优先队列中留下的最后一个元素便是根结点,将其取出返回
return queue.poll();
} /**
* 根据传入的结点遍历树
*
* @param node
* 遍历的起始结点
*/
public void ergodicTree(Node node) {
if (node != null) {
System.out.println(node.number);
// 递归遍历左孩子的次数
ergodicTree(node.leftChild);
// 递归遍历右孩子的次数
ergodicTree(node.rightChild);
}
} /**
* 根据哈夫曼树生成对应叶子结点的哈夫曼编码
*
* @param root
* 树的根结点
* @return 保存叶子结点的哈夫曼map
*/
public HashMap<Byte, String> tree2HfmMap(Node root) {
HashMap<Byte, String> hfmMap = new HashMap<>();
getHufmanCode(root, "", hfmMap);
return hfmMap;
} /**
* 根据输入的结点获得哈夫曼编码
*
* @param node
* 遍历的起始结点
* @param code
* 传入结点的编码类型
* @param hfmMap
* 用来保存字节对应的哈夫曼编码的map
*/
private void getHufmanCode(Node node, String code, HashMap<Byte, String> hfmMap) {
if (node != null) {
code += node.type;
// 当node为叶子结点的时候
if (node.leftChild == null && node.rightChild == null) {
hfmMap.put(node.by, code);
}
// 递归遍历左孩子的次数
getHufmanCode(node.leftChild, code, hfmMap);
// 递归遍历右孩子的次数
getHufmanCode(node.rightChild, code, hfmMap);
}
} }

三、创建一个模型类,用来保存被压缩文件的相关信息,包括被压缩文件的路径和该文件的哈夫曼树编码(HashMap对象),如下FileConfig.java:

  1. /**
  2. * 用来保存压缩时的文件路径和对应的字节哈夫曼编码映射
  3. *
  4. * @author Bill56
  5. *
  6. */
  7. public class FileConfig {
  8. // 文件路径
  9. private String filePath;
  10. // 文件字节的哈夫曼编码映射
  11. private HashMap<Byte, String> hfmCodeMap;
  12. /**
  13. * 构造方法
  14. *
  15. * @param filePath
  16. *            文件路径
  17. * @param hfmCodeMap
  18. *            文件字节的哈夫曼编码映射
  19. */
  20. public FileConfig(String filePath, HashMap<Byte, String> hfmCodeMap) {
  21. super();
  22. this.filePath = filePath;
  23. this.hfmCodeMap = hfmCodeMap;
  24. }
  25. public String getFilePath() {
  26. return filePath;
  27. }
  28. public void setFilePath(String filePath) {
  29. this.filePath = filePath;
  30. }
  31. public HashMap<Byte, String> getHfmCodeMap() {
  32. return hfmCodeMap;
  33. }
  34. public void setHfmCodeMap(HashMap<Byte, String> hfmCodeMap) {
  35. this.hfmCodeMap = hfmCodeMap;
  36. }
  37. @Override
  38. public String toString() {
  39. return "FileConfig [filePath=" + filePath + ", hfmCodeMap=" + hfmCodeMap + "]";
  40. }
  41. }
/**
* 用来保存压缩时的文件路径和对应的字节哈夫曼编码映射
*
* @author Bill56
*
*/
public class FileConfig { // 文件路径
private String filePath;
// 文件字节的哈夫曼编码映射
private HashMap<Byte, String> hfmCodeMap; /**
* 构造方法
*
* @param filePath
* 文件路径
* @param hfmCodeMap
* 文件字节的哈夫曼编码映射
*/
public FileConfig(String filePath, HashMap<Byte, String> hfmCodeMap) {
super();
this.filePath = filePath;
this.hfmCodeMap = hfmCodeMap;
} public String getFilePath() {
return filePath;
} public void setFilePath(String filePath) {
this.filePath = filePath;
} public HashMap<Byte, String> getHfmCodeMap() {
return hfmCodeMap;
} public void setHfmCodeMap(HashMap<Byte, String> hfmCodeMap) {
this.hfmCodeMap = hfmCodeMap;
} @Override
public String toString() {
return "FileConfig [filePath=" + filePath + ", hfmCodeMap=" + hfmCodeMap + "]";
} }

四、实现哈夫曼编码对文件的压缩和解压

完成了第二部分后,接下来便可以实现对文件实现压缩了。首先,需要扫描被压缩的文件,统计好每个字节对应所出现的次数,然后生成哈夫曼树,进而得到哈夫曼编码。最后,哈夫曼编码代替文件中的字节。可以将本部分的代码全部封装到一个FileUtil.java类中。以下的每一个点都是这个类的一个静态方法。

(一)统计被压缩文件中的字节及其出现的次数,用HashMap对象保存。

  1. /**
  2. * 根据指定的文件统计该文件中每个字节出现的次数,保存到一个HashMap对象中
  3. *
  4. * @param f
  5. *            要统计的文件
  6. * @return 保存次数的HashMap
  7. */
  8. public static HashMap<Byte, Integer> countByte(File f) {
  9. // 判断文件是否存在
  10. if (!f.exists()) {
  11. // 不存在,直接返回null
  12. return null;
  13. }
  14. // 执行到这表示文件存在
  15. HashMap<Byte, Integer> byteCountMap = new HashMap<>();
  16. FileInputStream fis = null;
  17. try {
  18. // 创建文件输入流
  19. fis = new FileInputStream(f);
  20. // 保存每次读取的字节
  21. byte[] buf = new byte[1024];
  22. int size = 0;
  23. // 每次读取1024个字节
  24. while ((size = fis.read(buf)) != -1) {
  25. // 循环每次读到的真正字节
  26. for (int i = 0; i < size; i++) {
  27. // 获取缓冲区的字节
  28. byte b = buf[i];
  29. // 如果map中包含了这个字节,则取出对应的值,自增一次
  30. if (byteCountMap.containsKey(b)) {
  31. // 获得原值
  32. int old = byteCountMap.get(b);
  33. // 先自增后入
  34. byteCountMap.put(b, ++old);
  35. } else {
  36. // map中不包含这个字节,则直接放入,且出现次数为1
  37. byteCountMap.put(b, 1);
  38. }
  39. }
  40. }
  41. } catch (FileNotFoundException e) {
  42. // TODO Auto-generated catch block
  43. e.printStackTrace();
  44. } catch (IOException e) {
  45. // TODO Auto-generated catch block
  46. e.printStackTrace();
  47. } finally {
  48. if (fis != null) {
  49. try {
  50. fis.close();
  51. } catch (IOException e) {
  52. // TODO Auto-generated catch block
  53. fis = null;
  54. }
  55. }
  56. }
  57. return byteCountMap;
  58. }
	/**
* 根据指定的文件统计该文件中每个字节出现的次数,保存到一个HashMap对象中
*
* @param f
* 要统计的文件
* @return 保存次数的HashMap
*/
public static HashMap<Byte, Integer> countByte(File f) {
// 判断文件是否存在
if (!f.exists()) {
// 不存在,直接返回null
return null;
}
// 执行到这表示文件存在
HashMap<Byte, Integer> byteCountMap = new HashMap<>();
FileInputStream fis = null;
try {
// 创建文件输入流
fis = new FileInputStream(f);
// 保存每次读取的字节
byte[] buf = new byte[1024];
int size = 0;
// 每次读取1024个字节
while ((size = fis.read(buf)) != -1) {
// 循环每次读到的真正字节
for (int i = 0; i < size; i++) {
// 获取缓冲区的字节
byte b = buf[i];
// 如果map中包含了这个字节,则取出对应的值,自增一次
if (byteCountMap.containsKey(b)) {
// 获得原值
int old = byteCountMap.get(b);
// 先自增后入
byteCountMap.put(b, ++old);
} else {
// map中不包含这个字节,则直接放入,且出现次数为1
byteCountMap.put(b, 1);
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
fis = null;
}
}
}
return byteCountMap;
}

 (二)实现对文件的压缩

对文件的压缩,应该是根据一个文件的引用和对应的哈夫曼编码来实现,并且将字节和对应的编码一并写入压缩后的文件头数据,以便之后做解压来读取。在实现这个方法之前,我们需要两个方法,就是根据01字符串转换成对应的字节,和根据字节生成对应的01字符串的方法。

1.根据01字符串生成对应的字节

  1. /**
  2. * 将字符串转成二进制字节的方法
  3. *
  4. * @param bString
  5. *            待转换的字符串
  6. * @return 二进制字节
  7. */
  8. private static byte bit2byte(String bString) {
  9. byte result = 0;
  10. for (int i = bString.length() - 1, j = 0; i >= 0; i--, j++) {
  11. result += (Byte.parseByte(bString.charAt(i) + "") * Math.pow(2, j));
  12. }
  13. return result;
  14. }
	/**
* 将字符串转成二进制字节的方法
*
* @param bString
* 待转换的字符串
* @return 二进制字节
*/
private static byte bit2byte(String bString) {
byte result = 0;
for (int i = bString.length() - 1, j = 0; i >= 0; i--, j++) {
result += (Byte.parseByte(bString.charAt(i) + "") * Math.pow(2, j));
}
return result;
}

 2.根据字节生成对应的01字符串

  1. /**
  2. * 将二字节转成二进制的01字符串
  3. *
  4. * @param b
  5. *            待转换的字节
  6. * @return 01字符串
  7. */
  8. public static String byte2bits(byte b) {
  9. int z = b;
  10. z |= 256;
  11. String str = Integer.toBinaryString(z);
  12. int len = str.length();
  13. return str.substring(len - 8, len);
  14. }
	/**
* 将二字节转成二进制的01字符串
*
* @param b
* 待转换的字节
* @return 01字符串
*/
public static String byte2bits(byte b) {
int z = b;
z |= 256;
String str = Integer.toBinaryString(z);
int len = str.length();
return str.substring(len - 8, len);
}

 3.实现压缩的方法

由于每8个01串生成一个字节,而被压缩文件最后的01串长度可能不是8的倍数,即不能被8整除,会出现不足8位的情况。这个时候,我们需要为其后面补0,补足8位,同时,还需要添加一个01串,该01串对应的字节应该是补0的次数(一定小于8)。

  1. /**
  2. * 将文件中的字节右字节哈夫曼map进行转换
  3. *
  4. * @param f
  5. *            待转换的文件
  6. * @param byteHfmMap
  7. *            该文件的字节哈夫曼map
  8. */
  9. public static FileConfig file2HfmCode(File f, HashMap<Byte, String> byteHfmMap) {
  10. // 声明文件输出流
  11. FileInputStream fis = null;
  12. FileOutputStream fos = null;
  13. try {
  14. System.out.println("正在压缩~~~");
  15. // 创建文件输入流
  16. fis = new FileInputStream(f);
  17. // 获取文件后缀前的名称
  18. String name = f.getName().substring(0, f.getName().indexOf("."));
  19. File outF = new File(f.getParent() + "\\" + name + "-压缩.txt");
  20. // 创建文件输出流
  21. fos = new FileOutputStream(outF);
  22. DataOutputStream dos = new DataOutputStream(fos);
  23. // 将哈夫曼编码读入到文件头部,并记录哈夫曼编码所占的大小
  24. Set<Byte> set = byteHfmMap.keySet();
  25. long hfmSize = 0;
  26. for (Byte bi : set) {
  27. // 先统计哈夫曼编码总共的所占的大小
  28. hfmSize += 1 + 4 + byteHfmMap.get(bi).length();
  29. }
  30. // 先将长度写入
  31. dos.writeLong(hfmSize);
  32. dos.flush();
  33. for (Byte bi : set) {
  34. // // 测试是否正确
  35. // System.out.println(bi + "\t" + byteHfmMap.get(bi));
  36. // 写入哈夫曼编码对应的字节
  37. dos.writeByte(bi);
  38. // 先将字符串长度写入
  39. dos.writeInt(byteHfmMap.get(bi).length());
  40. // 写入哈夫曼字节的编码
  41. dos.writeBytes(byteHfmMap.get(bi));
  42. dos.flush();
  43. }
  44. // 保存一次读取文件的缓冲数组
  45. byte[] buf = new byte[1024];
  46. int size = 0;
  47. // 保存哈弗吗编码的StringBuilder
  48. StringBuilder strBuilder = new StringBuilder();
  49. while ((size = fis.read(buf)) != -1) {
  50. // 循环每次读到的实际字节
  51. for (int i = 0; i < size; i++) {
  52. // 获取字节
  53. byte b = buf[i];
  54. // 在字节哈夫曼映射中找到该值,获得其hfm编码
  55. if (byteHfmMap.containsKey(b)) {
  56. String hfmCode = byteHfmMap.get(b);
  57. strBuilder.append(hfmCode);
  58. }
  59. }
  60. }
  61. // 将保存的文件哈夫曼编码按8个一字节进行压缩
  62. int hfmLength = strBuilder.length();
  63. // 获取需要循环的次数
  64. int byteNumber = hfmLength / 8;
  65. // 不足8位的数
  66. int restNumber = hfmLength % 8;
  67. for (int i = 0; i < byteNumber; i++) {
  68. String str = strBuilder.substring(i * 8, (i + 1) * 8);
  69. byte by = bit2byte(str);
  70. fos.write(by);
  71. fos.flush();
  72. }
  73. int zeroNumber = 8 - restNumber;
  74. if (zeroNumber < 8) {
  75. String str = strBuilder.substring(hfmLength - restNumber);
  76. for (int i = 0; i < zeroNumber; i++) {
  77. // 补0操作
  78. str += "0";
  79. }
  80. byte by = bit2byte(str);
  81. fos.write(by);
  82. fos.flush();
  83. }
  84. // 将补0的长度也记录下来保存到文件末尾
  85. String zeroLenStr = Integer.toBinaryString(zeroNumber);
  86. // 将01串转成字节
  87. byte zeroB = bit2byte(zeroLenStr);
  88. fos.write(zeroB);
  89. fos.flush();
  90. System.out.println("压缩完毕~~~");
  91. return new FileConfig(outF.getAbsolutePath(), byteHfmMap);
  92. } catch (FileNotFoundException e) {
  93. // TODO Auto-generated catch block
  94. e.printStackTrace();
  95. } catch (IOException e) {
  96. // TODO Auto-generated catch block
  97. e.printStackTrace();
  98. } finally {
  99. // 关闭流
  100. if (fis != null) {
  101. try {
  102. fis.close();
  103. } catch (IOException e) {
  104. // TODO Auto-generated catch block
  105. fis = null;
  106. }
  107. }
  108. // 关闭流
  109. if (fos != null) {
  110. try {
  111. fos.close();
  112. } catch (IOException e) {
  113. // TODO Auto-generated catch block
  114. fos = null;
  115. }
  116. }
  117. }
  118. return null;
  119. }
/**
* 将文件中的字节右字节哈夫曼map进行转换
*
* @param f
* 待转换的文件
* @param byteHfmMap
* 该文件的字节哈夫曼map
*/
public static FileConfig file2HfmCode(File f, HashMap<Byte, String> byteHfmMap) {
// 声明文件输出流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
System.out.println("正在压缩~~~");
// 创建文件输入流
fis = new FileInputStream(f);
// 获取文件后缀前的名称
String name = f.getName().substring(0, f.getName().indexOf("."));
File outF = new File(f.getParent() + "\\" + name + "-压缩.txt");
// 创建文件输出流
fos = new FileOutputStream(outF);
DataOutputStream dos = new DataOutputStream(fos);
// 将哈夫曼编码读入到文件头部,并记录哈夫曼编码所占的大小
Set<Byte> set = byteHfmMap.keySet();
long hfmSize = 0;
for (Byte bi : set) {
// 先统计哈夫曼编码总共的所占的大小
hfmSize += 1 + 4 + byteHfmMap.get(bi).length();
}
// 先将长度写入
dos.writeLong(hfmSize);
dos.flush();
for (Byte bi : set) {
// // 测试是否正确
// System.out.println(bi + "\t" + byteHfmMap.get(bi));
// 写入哈夫曼编码对应的字节
dos.writeByte(bi);
// 先将字符串长度写入
dos.writeInt(byteHfmMap.get(bi).length());
// 写入哈夫曼字节的编码
dos.writeBytes(byteHfmMap.get(bi));
dos.flush();
}
// 保存一次读取文件的缓冲数组
byte[] buf = new byte[1024];
int size = 0;
// 保存哈弗吗编码的StringBuilder
StringBuilder strBuilder = new StringBuilder();
while ((size = fis.read(buf)) != -1) {
// 循环每次读到的实际字节
for (int i = 0; i < size; i++) {
// 获取字节
byte b = buf[i];
// 在字节哈夫曼映射中找到该值,获得其hfm编码
if (byteHfmMap.containsKey(b)) {
String hfmCode = byteHfmMap.get(b);
strBuilder.append(hfmCode);
}
}
}
// 将保存的文件哈夫曼编码按8个一字节进行压缩
int hfmLength = strBuilder.length();
// 获取需要循环的次数
int byteNumber = hfmLength / 8;
// 不足8位的数
int restNumber = hfmLength % 8;
for (int i = 0; i < byteNumber; i++) {
String str = strBuilder.substring(i * 8, (i + 1) * 8);
byte by = bit2byte(str);
fos.write(by);
fos.flush();
}
int zeroNumber = 8 - restNumber;
if (zeroNumber < 8) {
String str = strBuilder.substring(hfmLength - restNumber);
for (int i = 0; i < zeroNumber; i++) {
// 补0操作
str += "0";
}
byte by = bit2byte(str);
fos.write(by);
fos.flush();
}
// 将补0的长度也记录下来保存到文件末尾
String zeroLenStr = Integer.toBinaryString(zeroNumber);
// 将01串转成字节
byte zeroB = bit2byte(zeroLenStr);
fos.write(zeroB);
fos.flush();
System.out.println("压缩完毕~~~");
return new FileConfig(outF.getAbsolutePath(), byteHfmMap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭流
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
fis = null;
}
}
// 关闭流
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
fos = null;
}
}
}
return null;
}

 (三)实现对已压缩文件的解压

首先应该读取已压缩文件的头数据,以获取其哈夫曼编码,然后通过哈夫曼编码来还原该文件。与压缩一样,在解压的时候,需要获取全部字节对应的01串,并将其保存到一个字符串对象中(最后8位除外),同时检测在压缩时候补0的个数(通过最后8位来获取),然后在字符串对象中舍弃多添加的0的个数。

  1. /**
  2. * 将已经压缩的文件进行解压,把哈夫曼编码重新转成对应的字节文件
  3. *
  4. * @param f
  5. *            待解压的文件
  6. * @param byteHfmMap
  7. *            保存字节的哈夫曼映射
  8. */
  9. public static void hfmCode2File(File f) {
  10. // 声明文件输出流
  11. FileInputStream fis = null;
  12. FileOutputStream fos = null;
  13. try {
  14. System.out.println("正在解压~~~");
  15. // 创建文件输入流
  16. fis = new FileInputStream(f);
  17. // 获取文件后缀前的名称
  18. String name = f.getName().substring(0, f.getName().indexOf("."));
  19. // 创建文件输出流
  20. fos = new FileOutputStream(f.getParent() + "\\" + name + "-解压.txt");
  21. DataInputStream dis = new DataInputStream(fis);
  22. long hfmSize = dis.readLong();
  23. // // 测试读取到的大小是否正确
  24. // System.out.println(hfmSize);
  25. // 用来保存从文件读到的哈夫曼编码map
  26. HashMap<Byte, String> byteHfmMap = new HashMap<>();
  27. for (int i = 0; i < hfmSize;) {
  28. byte b = dis.readByte();
  29. int codeLength = dis.readInt();
  30. byte[] bys = new byte[codeLength];
  31. dis.read(bys);
  32. String code = new String(bys);
  33. byteHfmMap.put(b, code);
  34. i += 1 + 4 + codeLength;
  35. // // 测试读取是否正确
  36. // System.out.println(b + "\t" + code + "\t" + i);
  37. }
  38. // 保存一次读取文件的缓冲数组
  39. byte[] buf = new byte[1024];
  40. int size = 0;
  41. // 保存哈弗吗编码的StringBuilder
  42. StringBuilder strBuilder = new StringBuilder();
  43. // fis.skip(hfmSize);
  44. while ((size = fis.read(buf)) != -1) {
  45. // 循环每次读到的实际字节
  46. for (int i = 0; i < size; i++) {
  47. // 获取字节
  48. byte b = buf[i];
  49. // 将其转成二进制01字符串
  50. String strBin = byte2bits(b);
  51. // System.out.printf("字节为:%d,对应的01串为:%s\n",b,strBin);
  52. strBuilder.append(strBin);
  53. }
  54. }
  55. String strTotalCode = strBuilder.toString();
  56. // 获取字符串总长度
  57. int strLength = strTotalCode.length();
  58. // 截取出最后八个之外的
  59. String strFact1 = strTotalCode.substring(0, strLength - 8);
  60. // 获取最后八个,并且转成对应的字节
  61. String lastEight = strTotalCode.substring(strLength - 8);
  62. // 得到补0的位数
  63. byte zeroNumber = bit2byte(lastEight);
  64. // 将得到的fact1减去最后的0的位数
  65. String strFact2 = strFact1.substring(0, strFact1.length() - zeroNumber);
  66. // 循环字节哈夫曼映射中的每一个哈夫曼值,然后在所有01串种进行匹配
  67. Set<Byte> byteSet = byteHfmMap.keySet();
  68. int index = 0;
  69. // 从第0位开始
  70. String chs = strFact2.charAt(0) + "";
  71. while (index < strFact2.length()) {
  72. // 计数器,用来判断是否匹配到了
  73. int count = 0;
  74. for (Byte bi : byteSet) {
  75. // 如果匹配到了,则跳出循环
  76. if (chs.equals(byteHfmMap.get(bi))) {
  77. fos.write(bi);
  78. fos.flush();
  79. break;
  80. }
  81. // 没有匹配到则计数器累加一次
  82. count++;
  83. }
  84. // 如果计数器值大于或鱼等map,说明没有匹配到
  85. if (count >= byteSet.size()) {
  86. index++;
  87. chs += strFact2.charAt(index);
  88. } else {
  89. // 匹配到了,则匹配下一个字符串
  90. if (++index < strFact2.length()) {
  91. chs = strFact2.charAt(index) + "";
  92. }
  93. }
  94. }
  95. System.out.println("解压完毕~~~");
  96. // for (Byte hfmByte : byteSet) {
  97. // String strHfmCode = byteHfmMap.get(hfmByte);
  98. // strFact2 = strFact2.replaceAll(strHfmCode,
  99. // String.valueOf(hfmByte));
  100. // }
  101. // fos.write(strFact2.getBytes());
  102. // fos.flush();
  103. } catch (FileNotFoundException e) {
  104. // TODO Auto-generated catch block
  105. e.printStackTrace();
  106. } catch (IOException e) {
  107. // TODO Auto-generated catch block
  108. e.printStackTrace();
  109. } finally {
  110. // 关闭流
  111. if (fis != null) {
  112. try {
  113. fis.close();
  114. } catch (IOException e) {
  115. // TODO Auto-generated catch block
  116. fis = null;
  117. }
  118. }
  119. // 关闭流
  120. if (fos != null) {
  121. try {
  122. fos.close();
  123. } catch (IOException e) {
  124. // TODO Auto-generated catch block
  125. fos = null;
  126. }
  127. }
  128. }
  129. }
	/**
* 将已经压缩的文件进行解压,把哈夫曼编码重新转成对应的字节文件
*
* @param f
* 待解压的文件
* @param byteHfmMap
* 保存字节的哈夫曼映射
*/
public static void hfmCode2File(File f) {
// 声明文件输出流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
System.out.println("正在解压~~~");
// 创建文件输入流
fis = new FileInputStream(f);
// 获取文件后缀前的名称
String name = f.getName().substring(0, f.getName().indexOf("."));
// 创建文件输出流
fos = new FileOutputStream(f.getParent() + "\\" + name + "-解压.txt");
DataInputStream dis = new DataInputStream(fis);
long hfmSize = dis.readLong();
// // 测试读取到的大小是否正确
// System.out.println(hfmSize);
// 用来保存从文件读到的哈夫曼编码map
HashMap<Byte, String> byteHfmMap = new HashMap<>();
for (int i = 0; i < hfmSize;) {
byte b = dis.readByte();
int codeLength = dis.readInt();
byte[] bys = new byte[codeLength];
dis.read(bys);
String code = new String(bys);
byteHfmMap.put(b, code);
i += 1 + 4 + codeLength;
// // 测试读取是否正确
// System.out.println(b + "\t" + code + "\t" + i);
}
// 保存一次读取文件的缓冲数组
byte[] buf = new byte[1024];
int size = 0;
// 保存哈弗吗编码的StringBuilder
StringBuilder strBuilder = new StringBuilder();
// fis.skip(hfmSize);
while ((size = fis.read(buf)) != -1) {
// 循环每次读到的实际字节
for (int i = 0; i < size; i++) {
// 获取字节
byte b = buf[i];
// 将其转成二进制01字符串
String strBin = byte2bits(b);
// System.out.printf("字节为:%d,对应的01串为:%s\n",b,strBin);
strBuilder.append(strBin);
}
}
String strTotalCode = strBuilder.toString();
// 获取字符串总长度
int strLength = strTotalCode.length();
// 截取出最后八个之外的
String strFact1 = strTotalCode.substring(0, strLength - 8);
// 获取最后八个,并且转成对应的字节
String lastEight = strTotalCode.substring(strLength - 8);
// 得到补0的位数
byte zeroNumber = bit2byte(lastEight);
// 将得到的fact1减去最后的0的位数
String strFact2 = strFact1.substring(0, strFact1.length() - zeroNumber);
// 循环字节哈夫曼映射中的每一个哈夫曼值,然后在所有01串种进行匹配
Set<Byte> byteSet = byteHfmMap.keySet();
int index = 0;
// 从第0位开始
String chs = strFact2.charAt(0) + "";
while (index < strFact2.length()) {
// 计数器,用来判断是否匹配到了
int count = 0;
for (Byte bi : byteSet) {
// 如果匹配到了,则跳出循环
if (chs.equals(byteHfmMap.get(bi))) {
fos.write(bi);
fos.flush();
break;
}
// 没有匹配到则计数器累加一次
count++;
}
// 如果计数器值大于或鱼等map,说明没有匹配到
if (count >= byteSet.size()) {
index++;
chs += strFact2.charAt(index);
} else {
// 匹配到了,则匹配下一个字符串
if (++index < strFact2.length()) {
chs = strFact2.charAt(index) + "";
}
}
}
System.out.println("解压完毕~~~");
// for (Byte hfmByte : byteSet) {
// String strHfmCode = byteHfmMap.get(hfmByte);
// strFact2 = strFact2.replaceAll(strHfmCode,
// String.valueOf(hfmByte));
// }
// fos.write(strFact2.getBytes());
// fos.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭流
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
fis = null;
}
}
// 关闭流
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
fos = null;
}
}
}
}

 (四)将第(一)中得到的字节和次数map对象生成哈夫曼树编码,实现压缩,并且保存到FileConfig对象中

  1. public static FileConfig yasuo(File f) {
  2. HashMap<Byte, Integer> map = FileUtil.countByte(f);
  3. Tree tree = new Tree();
  4. // 构建优先队列
  5. PriorityQueue<Node> queue = tree.map2Queue(map);
  6. // 构建树
  7. Node root = tree.queue2Tree(queue);
  8. // 获得字节的哈夫曼编码map
  9. // tree.ergodicTree(root);
  10. HashMap<Byte, String> hfmMap = tree.tree2HfmMap(root);
  11. // Set<Byte> set = hfmMap.keySet();
  12. // for (Byte b : set) {
  13. // System.out.printf("字节为:%d,哈夫曼编码为:%s\n", b, hfmMap.get(b));
  14. // }
  15. FileConfig fc = FileUtil.file2HfmCode(f, hfmMap);
  16. return fc;
  17. }
public static FileConfig yasuo(File f) {
HashMap<Byte, Integer> map = FileUtil.countByte(f);
Tree tree = new Tree();
// 构建优先队列
PriorityQueue<Node> queue = tree.map2Queue(map);
// 构建树
Node root = tree.queue2Tree(queue);
// 获得字节的哈夫曼编码map
// tree.ergodicTree(root);
HashMap<Byte, String> hfmMap = tree.tree2HfmMap(root);
// Set<Byte> set = hfmMap.keySet();
// for (Byte b : set) {
// System.out.printf("字节为:%d,哈夫曼编码为:%s\n", b, hfmMap.get(b));
// }
FileConfig fc = FileUtil.file2HfmCode(f, hfmMap);
return fc;
}

 (五)实现解压的具体算法

  1. public static void jieya(String filePath) {
  2. File f = new File(filePath);
  3. FileUtil.hfmCode2File(f);
  4. }
	public static void jieya(String filePath) {
File f = new File(filePath);
FileUtil.hfmCode2File(f);
}

五、创建一个测试类,用来压缩一个文件,同时对被压缩的文件再次解压,查看耗时

  1. /**
  2. * 测试一些算法的类
  3. *
  4. * @author Bill56
  5. *
  6. */
  7. public class Test {
  8. public static void main(String[] args) {
  9. File f = new File("C:\\Users\\Bill56\\Desktop\\file.txt");
  10. long startTime = System.currentTimeMillis();
  11. FileConfig fc = ExeUtilFile.yasuo(f);
  12. ExeUtilFile.jieya(fc.getFilePath());
  13. long endTime = System.currentTimeMillis();
  14. System.out.println("压缩和解压共花费时间为:" + (endTime - startTime) + "ms");
  15. }
  16. }
/**
* 测试一些算法的类
*
* @author Bill56
*
*/
public class Test { public static void main(String[] args) {
File f = new File("C:\\Users\\Bill56\\Desktop\\file.txt");
long startTime = System.currentTimeMillis();
FileConfig fc = ExeUtilFile.yasuo(f);
ExeUtilFile.jieya(fc.getFilePath());
long endTime = System.currentTimeMillis();
System.out.println("压缩和解压共花费时间为:" + (endTime - startTime) + "ms");
} }

 运行结果:


  
六、缺陷
本博文所采用的压缩算法是在内存中进行转换后全部存储到一个字符串对象中,然后再去写入文件,解压算法也是一样,所以对内存的开销很大,时间开销也大,所以这里只是提供一种实现的可能性,读者千万不要将其应用到实际中。如要应用,应先限定能要压缩的文件大小,如不超过20M等。
 
谢谢您的关注和阅读,文章不当之处还请您不吝赐教~~~
 

java实现哈弗曼树和哈夫曼树压缩的更多相关文章

  1. 20172332 2017-2018-2 《程序设计与数据结构》Java哈夫曼编码实验--哈夫曼树的建立,编码与解码

    20172332 2017-2018-2 <程序设计与数据结构>Java哈夫曼编码实验--哈夫曼树的建立,编码与解码 哈夫曼树 1.路径和路径长度 在一棵树中,从一个结点往下可以达到的孩子 ...

  2. Java数据结构(十二)—— 霍夫曼树及霍夫曼编码

    霍夫曼树 基本介绍和创建 基本介绍 又称哈夫曼树,赫夫曼树 给定n个权值作为n个叶子节点,构造一棵二叉树,若该树的带权路径长度(wpl)达到最小,称为最优二叉树 霍夫曼树是带权路径长度最短的树,权值较 ...

  3. Java 树结构实际应用 二(哈夫曼树和哈夫曼编码)

     赫夫曼树 1 基本介绍 1) 给定 n 个权值作为 n 个叶子结点,构造一棵二叉树,若该树的带权路径长度(wpl)达到最小,称这样的二叉树为 最优二叉树,也称为哈夫曼树(Huffman Tree), ...

  4. 10: java数据结构和算法: 构建哈夫曼树, 获取哈夫曼编码, 使用哈夫曼编码原理对文件压缩和解压

    最终结果哈夫曼树,如图所示: 直接上代码: public class HuffmanCode { public static void main(String[] args) { //获取哈夫曼树并显 ...

  5. [数据结构与算法]哈夫曼(Huffman)树与哈夫曼编码

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  6. 哈夫曼(huffman)树和哈夫曼编码

    哈夫曼树 哈夫曼树也叫最优二叉树(哈夫曼树) 问题:什么是哈夫曼树? 例:将学生的百分制成绩转换为五分制成绩:≥90 分: A,80-89分: B,70-79分: C,60-69分: D,<60 ...

  7. 数据结构图文解析之:哈夫曼树与哈夫曼编码详解及C++模板实现

    0. 数据结构图文解析系列 数据结构系列文章 数据结构图文解析之:数组.单链表.双链表介绍及C++模板实现 数据结构图文解析之:栈的简介及C++模板实现 数据结构图文解析之:队列详解与C++模板实现 ...

  8. 哈夫曼(Huffman)树和哈夫曼编码

    一.哈夫曼(Huffman)树和哈夫曼编码 1.哈夫曼树(Huffman)又称最优二叉树,是一类带权路径长度最短的树, 常用于信息检测. 定义: 结点间的路径长度:树中一个结点到另一个结点之间分支数目 ...

  9. c++实现哈夫曼树,哈夫曼编码,哈夫曼解码(字符串去重,并统计频率)

    #include <iostream> #include <iomanip> #include <string> #include <cstdlib> ...

随机推荐

  1. Android开发多媒体应用之SoundPool的使用的代码

    内容过程中,把写内容过程中比较好的内容段记录起来,下面的内容是关于Android开发多媒体应用之SoundPool的使用的内容,希望对各位也有用途. public class MainActivity ...

  2. redis中算法之——MurmurHash2算法

    MurmurHash算法由Austin Appleby发明于2008年,是一种非加密hash算法,适用于基于hash查找的场景.murmurhash最新版本是MurMurHash3,支持32位,64位 ...

  3. js中this那些事儿

    前几天写东西由于恶趣味作祟将所有的函数全部封装在json中,起初好好的,函数B也可以调用函数A的内容,不过在写一个点击事件时出现了意外, 代码如下: var $ ={ "A":fu ...

  4. selenium+Python(处理html5的视频播放)

    Webdriver支持在指定的浏览器测试HTML5,另外可以用JavaScript来测试这些功能,这样就可以在任何浏览器上测试HTML5 多数浏览器使用控件来播放视频,但是不同浏览器需要使用不同的插件 ...

  5. 基础selenium+Python(定位、等待、打印)

    1.第一个脚本 # coding = utf-8 from selenium import webdriver browser = webdriver.Firefox() browser.get(&q ...

  6. unity收集log工具

    参考 yusong:http://www.xuanyusong.com/archives/2477 凉鞋     :https://www.cnblogs.com/liangxiegame/p/Uni ...

  7. shiro的授权

    1.授权的流程 2.三种授权方式 1.编程式:通过写if/else 授权代码块完成: Subject subject = SecurityUtils.getSubject(); if(subject. ...

  8. 手动修改user-agent

    1. 在浏览器地址栏输入 about:config.弹出对话框:

  9. WebDriverWait介绍

    转自:https://www.cnblogs.com/ella-yao/p/7778678.html WebDriverWait介绍 package com.test.elementwait; imp ...

  10. UML关系

    UML关系详解 1.关联关系(association) 连接模型元素及链接实例,用一条实线来表示 2.依赖关系(dependency) 表示一个元素以某种方式依赖于另一个元素,用一条虚线加箭头来表示 ...