huffman压缩 java_java-Huffman代码将位写入文件以进行压缩

我被要求使用霍夫曼代码压缩输入文件并将其写入输出文件.我已经完成了霍夫曼树的结构并生成了霍夫曼代码.但是我不知道如何将这些代码写入文件,以使文件的大小小于原始文件的大小.

现在,我有了以字符串表示形式的代码(例如,“ 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();

}

标签:huffman-code,greedy,compression,java,algorithm

来源: https://codeday.me/bug/20191111/2020174.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值