我被要求使用哈夫曼编码压缩输入文件并将其写入输出文件。我已完成哈夫曼树结构的实现和哈夫曼编码的生成。但我不知道如何将这些代码写入文件,使得文件比原始文件更小。
目前,我把这些代码表示为字符串(例如,字符'c'的哈夫曼编码为“0100”)。请有人帮助我将这些位写入文件中。
目前,我把这些代码表示为字符串(例如,字符'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();
}