霍夫曼代码将位写入文件以进行压缩
Huffman Code writing bits to a file for compression
我被要求使用霍夫曼代码压缩输入文件并将其写入输出文件。我已经完成了霍夫曼树结构的实现和霍夫曼代码的生成。但我不知道如何将这些代码写入文件,使文件的大小小于原始文件。
现在我有字符串表示的代码(例如 '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) 中逐位写入。
编辑
对于您的具体问题,要保存每个角色的霍夫曼代码,如果您不想使用其他花哨的东西,您可以简单地使用它 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();
}
我被要求使用霍夫曼代码压缩输入文件并将其写入输出文件。我已经完成了霍夫曼树结构的实现和霍夫曼代码的生成。但我不知道如何将这些代码写入文件,使文件的大小小于原始文件。
现在我有字符串表示的代码(例如 '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) 中逐位写入。
编辑
对于您的具体问题,要保存每个角色的霍夫曼代码,如果您不想使用其他花哨的东西,您可以简单地使用它 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();
}