简体   繁体   English

如何将霍夫曼编码的字符写入文件?

[英]How do I write Huffman encoded characters to a file?

I am trying to read the contents of file and then write them to a different file with Huffman coding. 我正在尝试读取文件的内容,然后使用霍夫曼编码将它们写入另一个文件。 So I have created a Huffman Tree, with each node containing the character, frequency of the character, and a binary string representing the frequency. 因此,我创建了一个霍夫曼树,每个节点包含字符,字符频率以及代表频率的二进制字符串。 What I am having trouble understanding is writing the Huffman coded characters to a file. 我无法理解的是将霍夫曼编码的字符写入文件。

I tried writing the binary string to the file but realized that it was just writing string and not actually the coded data. 我尝试将二进制字符串写入文件,但意识到它只是在写入字符串,而不是实际在编码数据。 So I then converted the binary strings to bytes and wrote the bytes to the file but that would just give me a blank file the same size as the original. 因此,我然后将二进制字符串转换为字节,并将字节写入文件,但这只会给我一个与原始文件大小相同的空白文件。 I feel like I am missing something when it comes to actually writing the file. 在实际写入文件时,我感觉好像丢失了一些东西。

Edit: After taking a look back at my code I realized that my Tree wasn't completely correct and I'm now able to (I think) combine bit string together to make a byte array that I can write to a file (code updated to reflect that). 编辑:回顾一下我的代码后,我意识到我的树并不完全正确,我现在能够(我认为)将位字符串组合在一起以组成一个字节数组,可以将其写入文件(更新了代码反映这一点)。 For my test case I am reading in the text AAA_BB_C but when I look at the file the output is <0x1e> . 对于我的测试用例,我正在读取文本AAA_BB_C但是当我查看文件时,输出为<0x1e> I'm not sure what this means. 我不确定这是什么意思。 I was expecting the same output of the original file, just a smaller size. 我期望原始文件的输出相同,只是尺寸较小。

public static void writeFile(HuffTree tree) {
    String bin = ""; // String of entire binary code
    int spot = 0; // Spot in array
    byte[] bytes = new byte[256]; // byte array
    try {
        FloatileWriter writer = new FileWriter("test(encoded).txt");

            // Gets Binary String of each Character in the file
            for(int i = 0; i < fileText.length(); i++) {
                bin += tree.findDataBinary(fileText.charAt(i));
            }

            // Takes each bit and adds to byte array 
            System.out.println(bin);
            while(bin.length() > 7) {
                String temp = bin.substring(0, 7);
                bin = bin.substring(7, bin.length());
                bytes[spot] = Byte.parseByte(temp, 2);
                spot++;
            }

            // Writes bytes to file
            for(int i = 0; i <= spot; i++) {
                writer.write(bytes[i]);
            }
            writer.close();
    } catch(IOException e) {
        System.out.println("IOException!");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM