Java saving huffman encoded text to file

I'm working on a huffman compression and decompression application in java. So far I got the encoding and decoding working. It converts a big input text to it's encoded binary text. This is a String of 1's and 0's. For example:

String originaltext = "Hello I am trying to program a huffman application and..."

String encodedtext = "1100001110001111011010100110100110...." It's a pretty long string.

Now I want to save the string to a file as binary file to reduce the size. But when I try do this, the size will be way bigger then the original text size. Instead I need the size smaller then the original file size. After saving the encodedtext to a file I need to read the binary file back in and convert it to the encodedText string to deconvert it with my huffmantree method.

How can I save the binary string to a binary file which size is then smaller then the original size? And how do read the file in and convert the binary code to the encodedString text?

1 answer

  • answered 2018-04-14 14:25 Ridcully

    Probably you're writing your string of 1 and 0 as a string, which will result in 1 byte per 1 or 0.

    You need to convert those 1 and 0 to bytes (i.e. convert groups of eight 1 or 0 into 1 byte and write those bytes.