java - 霍夫曼代码将位写入文件以进行压缩

标签 java algorithm compression huffman-code greedy

我被要求使用霍夫曼代码压缩输入文件并将其写入输出文件。我已经完成了霍夫曼树结构的实现和霍夫曼代码的生成。但我不知道如何将这些代码写入文件,使文件的大小小于原始文件。

现在我有字符串表示形式的代码(例如,'c' 的霍夫曼代码是“0100”)。有人请帮我把这些位写成 文件。

最佳答案

这里是将比特流(霍夫曼编码的输出)写入文件的可能实现。

class BitOutputStream {

    private OutputStream out;
    private boolean[] buffer = new boolean[8];
    private int count = 0;

    public BitOutputStream(OutputStream out) {
        this.out = out;
    }

    public void write(boolean x) throws IOException {
        this.count++;
        this.buffer[8-this.count] = x;
        if (this.count == 8){
            int num = 0;
            for (int index = 0; index < 8; index++){
                num = 2*num + (this.buffer[index] ? 1 : 0);
            }

            this.out.write(num - 128);

            this.count = 0;
        }
    }

    public void close() throws IOException {
        int num = 0;
        for (int index = 0; index < 8; index++){
            num = 2*num + (this.buffer[index] ? 1 : 0);
        }

        this.out.write(num - 128);

        this.out.close();
    }

}

通过调用 write 方法,您将能够在文件 (OutputStream) 中逐位写入。

编辑

对于您的特定问题,要保存每个角色的霍夫曼代码,如果您不想使用其他花哨的类,您可以简单地使用它 -

String huffmanCode = "0100"; // lets say its huffman coding output for c

BitSet huffmanCodeBit = new BitSet(huffmanCode.length());

for (int i = 0; i < huffmanCode.length(); i++) {
    if(huffmanCode.charAt(i) == '1')
        huffmanCodeBit.set(i);
}
String path = Resources.getResource("myfile.out").getPath();
ObjectOutputStream outputStream = null;
try {
    outputStream = new ObjectOutputStream(new FileOutputStream(path));
    outputStream.writeObject(huffmanCodeBit);
} catch (IOException e) {
    e.printStackTrace();
}

关于java - 霍夫曼代码将位写入文件以进行压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43421273/

相关文章:

java - Android FirebaseRecyclerView 实现搜索用户功能时遇到的问题

java - 如何有效地生成一组具有预定义分布的唯一随机数?

ruby - 在数组中查找重复项——如何更快?

python - 使用 PyLZMA 和 py7zlib 将文件夹递归压缩为 7z

apache-spark - parquet支持哪些压缩类型

java - 不带断言编译

java - Spring Validation - 用于解决字段错误的类级别验证

java - 未找到 Maven 'resources' 文件夹

java - 是否有在一棵树中处理不同类别的做法? (Java 或通用)

java - 使用 FileOutputStream 时出现 FileNotFoundException