I'm currently working with a Huffman Tree to compress/decompress text files. Currently my problem is that when writing bytes and reading them, I lose any leading 0's in my numbers.
In my OutputStream class, my writeBit()
method, I am fed one bit at a time and when my count of bits reaches 8, I write the byte to the file. Currently using a String to build this binary number, although the problem occurs when actually writing the bit.
HuffmanOutputStream.java:
/**
* Created by Sully on 3/20/2017.
*/
import java.io.IOException;
public class HuffmanOutputStream extends BitOutputStream {
private int count = 0;
private String bytes = "";
public HuffmanOutputStream(String filename, String tree, int totalChars) {
super(filename);
try {
d.writeUTF(tree);
d.writeInt(totalChars);
} catch (IOException e) {
}
}
public void writeBit(int bit) {
//PRE bit == 0 || bit == 1
if (count < 8) {
bytes += bit;
count++;
}
try {
if (count == 8) {
d.writeByte(Integer.parseInt(bytes, 2));
count = 0;
bytes = "";
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
}
}
An example of when things go wrong, for my text file, the first byte that I construct is 01100001, although when I use Integer.parseInt(byte,2), the integer given is 97, which when it is then read as a binary number, only returns 1100001. As Huffman Trees rely on these 0's being included, how can I keep this 0 in place? Also to make sure that it is read correctly with the 0's remaining in place?
HuffmanInputStream.java:
/**
* Created by Sully on 3/20/2017.
*/
import java.io.IOException;
public class HuffmanInputStream extends BitInputStream {
private String tree;
private int totalChars;
private int currentByte;
private int bitCount;
private static final int BYTE_SIZE = 8;
private int[] bufferedBits = new int[BYTE_SIZE];
public HuffmanInputStream(String filename) {
super(filename);
try {
tree = d.readUTF();
totalChars = d.readInt();
currentByte = 0;
bitCount = 8;
} catch (IOException e) {
}
}
public int readBit() {
if (currentByte == -1) {
return -1;
}
if (bitCount == 8) {
try {
currentByte = d.read();
if(currentByte == -1){
return -1;
}
String binary = Integer.toBinaryString(currentByte);
for (int x = 0; x < binary.length(); x++) {
bufferedBits[x] = Character.valueOf(binary.charAt(x));
}
bitCount = 0;
} catch (IOException e) {
e.printStackTrace();
}
}
int val = bufferedBits[bitCount];
bitCount++;
return val % 2;
}
public String getTree() {
return tree;
}
public int totalChars() {
return totalChars;
}
public void close() {
try {
d.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I know it's a bit lengthy of a question but any help is greatly appreciated!