我被要求使用霍夫曼代码压缩输入文件并将其写入输出文件.我已经完成了霍夫曼树的结构并生成了霍夫曼代码.但是我不知道如何将这些代码写入文件,以使文件的大小小于原始文件的大小.
现在,我有了以字符串表示形式的代码(例如,“ 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();
}