public class HuffmanCode {
//将赫夫曼编码存放在Map<Byte,String>中,形如: a==>100
static Map<Byte,String> huffmanCode = new HashMap<>();
static StringBuilder stringBuilder = new StringBuilder();//用于拼接路径
public static void main(String[] args) {
// String content = "i like like like java do you like a java";//长度:40
// //将字符串转成byte数组
// byte[] contentByte = content.getBytes();
// //压缩
// byte[] zip = huffmanZip(contentByte);
// System.out.println(Arrays.toString(zip));
// //解压
// byte[] decode = decode(huffmanCode, zip);
// System.out.println(new String(decode));
//对文件进行压缩
// String fileSrc = "D:\\test.jpeg";
// String desSrc = "D:\\test.zip";
// fileZip(fileSrc,desSrc);
// System.out.println("压缩成功");
//对文件进行解压
String fileSrc = "D:\\test.zip";
String desSrc = "D:\\test2.jpeg";
unZipFile(fileSrc,desSrc);
System.out.println("解压成功");
}
/**
* 对文件进行赫夫曼编码压缩
* @param fileSrc 需要压缩文件的路径
* @param desSrc 压缩后文件的输出路径
*/
public static void fileZip(String fileSrc,String desSrc){
//创建文件输入流
InputStream input = null;
//创建文件输出流,存放压缩文件
OutputStream output = null;
//创建对象输出流,以对象流的方式写入赫夫曼编码,为了以后恢复文件的时候使用
ObjectOutput obput = null;
try {
input = new FileInputStream(fileSrc);//拿到文件的输入流
byte[] bytes = new byte[input.available()];
input.read(bytes);
//对文件的字节数组进行压缩
byte[] huffmanBytes = huffmanZip(bytes);
output = new FileOutputStream(desSrc);
obput = new ObjectOutputStream(output);
obput.writeObject(huffmanBytes);//把赫夫曼编码后的字节数组写入压缩文件
obput.writeObject(huffmanCode);//同时把赫夫曼编码写入压缩文件,以备以后解压
} catch (Exception e) {
Syst
使用赫夫曼编码对数组、文件等进行压缩
最新推荐文章于 2023-06-11 10:13:43 发布