【发布时间】:2015-10-12 17:11:19
【问题描述】:
我正在尝试使用 Huffman 编码实现文件压缩。目前,我将标题写入压缩文件的第一行,然后写入编码的二进制字符串(即具有二进制编码值的字符串)。
但是,我的文件大小并没有减小文件大小,而是增加了每个字符,例如“a”,我正在编写其相应的二进制文件,例如 01010001,它占用更多空间。
如何以减少空间的方式将其写入文件?
这是我的代码
public void write( String aWord ) {
counter++;
String content;
byte[] contentInBytes;
//Write header before writing file contents
if ( counter == 1 )
{
//content gets the header in String format from the tree
content = myTree.myHeader;
contentInBytes = content.getBytes();
try {
fileOutputStream.write(contentInBytes);
fileOutputStream.write(System.getProperty("line.separator").getBytes());
} catch (IOException e) {
System.err.println(e);
}
}
//content gets the encoded binary in String format from the tree
content = myTree.writeMe(aWord);
contentInBytes = content.getBytes();
try {
fileOutputStream.write(contentInBytes);
fileOutputStream.write(System.getProperty("line.separator").getBytes());
} catch (IOException e) {
System.err.println(e);
}
}
示例输入文件:
abc
aef
aeg
压缩文件:
{'g':"010",'f':"011",'c':"000",'b':"001",'e':"10",'a':"11"}
11001000
1110011
1110010
【问题讨论】:
-
这个有调用代码吗?你是如何填充 myTree 的?
-
是的,有一个包含字符及其值的链表,并且“内容”正在获取该特定行的正确二进制值。我唯一的问题是这里的空间,所以我需要以一种比现在占用更少空间的方式写入文件,因为我当前的压缩文件最终是原始文件大小的 4-5 倍
-
因此您可以测试或登录以验证 myTree 具有唯一成员...例如"a" 不重复。
-
是的,树中没有重复的实例。我只需要高效地完成写作。
-
曾经的解决方案是使用 ASCII 字符集 0-255 将位分组为字节 (8).. 因为现在当您写入 0 时,实际上是在写入字节 48。
标签: java file compression huffman-code