哈夫曼编码文件压缩解压
没整懂
这份代码竟然只能压缩文本文件,而且内容不能包含中文,不能解压大于 8 k 的zip压缩文件还有就是如果使用哈夫曼编码压缩的内容重复率不高,压缩的效果不明显,如果内容的重复率高压缩的效果好点
public static void main(String[] args) {
// 只能压缩txt,压缩的文件不能有中文
String srcFile = "F:\\Temp\\test2.txt";
String dstFile = "F:\\Temp\\hufmanTxt.zip";
FileZip(srcFile, dstFile);
String srcFile2 = "F:\\Temp\\hufmanTxt.zip";
String dstFile2 = "F:\\Temp\\jieya.txt";
FileUnZip(srcFile2, dstFile2);
}
/**
* 调用封装
*/
public static byte[] hufmanZip(byte[] bytes){
List<hufNode> nodes = strToList(new String(bytes));
hufNode root = createHufmanTree(nodes);
getCodes(root, "", context);
byte[] zip = zip(bytes, codeMap);
return zip;
}
/**
* 哈夫曼编码 - 文件压缩
* @param srcFile
* @param dstFile
*/
public static void FileZip(String srcFile, String dstFile){
InputStream is = null;
ObjectOutputStream oos = null;
FileOutputStream os = null;
try {
// 输入流
is = new FileInputStream(srcFile);
// 创建 byte 数组接收输入流文件
byte[] b = new byte[is.available()];
// 读入 b 数组中
is.read(b);
// 哈夫曼编码处理后的 字节数组
byte[] hufmanCodes = hufmanZip(b);
os = new FileOutputStream(dstFile);
// 输出流
oos = new ObjectOutputStream(os);
oos.writeObject(hufmanCodes);
// 把哈夫曼编码表也写入起来,文件恢复操作需要用到
oos.writeObject(codeMap);
System.out.println("压缩成功!! ");
} catch (Exception e) {
System.out.println(e.getMessage());
}finally {
try {
oos.close();
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 哈夫曼编码 -- 文件解压
* @param srcFile
* @param dstFile
*/
public static void FileUnZip(String srcFile, String dstFile){
InputStream is = null;
ObjectInputStream ois = null;
OutputStream os = null;
try {
is = new FileInputStream(srcFile);
ois = new ObjectInputStream(is);
// 哈夫曼编码处理后的字节数组
byte[] b = (byte[]) ois.readObject();
// 存入 b
Map<Byte, String> hufmanMap = (Map<Byte, String>) ois.readObject();
// 解析
byte[] decode = decode(hufmanMap, b);
os = new FileOutputStream(dstFile);
os.write(decode);
System.out.println("解压成功~~");
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
os.close();
ois.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}