adonayresom
adonayresom

Reputation: 290

Huffman Code writing bits to a file for compression

I was asked to use huffman code to compress an input file and write it to an output file. I have finished implementing the huffman tree structure and generating the huffman codes. But I dont know how to write those codes into a file so that the file is less in size than the original file.

Right now I have the codes in string representation (e.g huffman code for 'c' is "0100"). Someone please help me write those bits into a file.

Upvotes: 3

Views: 2959

Answers (1)

Kaidul
Kaidul

Reputation: 15915

Here a possible implementation to write stream of bits(output of Huffman coding) into file.

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();
    }

}

By calling write method you will able to write bit by bit in a file (OutputStream).

Edit

For your specific problem, to save each character's huffman code you can simply use this if you don't want to use some other fancy class -

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();
}

Upvotes: 3

Related Questions