我想用哈夫曼编码压缩文件,我已经得到每个字符对应的二进制编码了,但我想不出什么好办法将二进制编码写入到文件里。我发现Java IO的类的读写单位最小是byte,但我想读写的是更小的bit,请问有什么高效的办法吗?你可以用任意觉得方便的方式保存每个字符的二进制编码。我用了boolean[],你可以用string或什么别的。
for (int i = 0; i < text.length(); i++)
{
char c = text.charAt(i);
boolean[] bin=map.get(c);
//???
}

解决方案 »

  1.   

    每个字符对应的二进制编码那就用byte[] 写吧。比如8K一次。
      

  2.   

    内存计算,缓冲到byte[] ,满了再写到文件里。
      

  3.   

    InputStream的方法:read(byte[] b,int off,int len);
      

  4.   


    package com.io;import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;public class ByteReadFileTest {
    public static void main(String[] args) throws IOException {
    String dir = "D:/workspace/TestProject/src/com/io/ByteReadFileTest.java";
    String src = "D:/workspace/TestProject/src/com/io/out.java";
    InputStream input = new FileInputStream(dir);
    OutputStream out = new FileOutputStream(src);
    int length = 0;
    byte[] b = new byte[1024];// 缓冲区
    while ((length = input.read(b)) != -1) {
    System.out.print(new String(b, 0, length));
    out.write(b, 0, length);// 重要...
    out.flush();
    }
    out.close();
    }
    }
    byte[] b = new byte[1024];// 缓冲区
    缓冲区越大速度越快。new byte[1024*1024];
      

  5.   

    思路就是把8个比特合为一个字节,然后按字节写。具体合并的算法有好有坏。我这里抛砖引玉,给出网上找到的(我可能自己有修改的)实现。
    import java.io.IOException;
    import java.io.OutputStream;/**
     * A stream where bits can be written to.
     */
    public final class BitOutputStream extends OutputStream
    { private final OutputStream output; // Underlying byte stream to write to private int currentByte; // Always in the range 0x00 to 0xFF private int hasBits; // Always between 0 and 7, inclusive public BitOutputStream(OutputStream out)
    {
    if (out == null)
    throw new NullPointerException("OutputStream不可为null。");
    output = out;
    currentByte = 0;
    hasBits = 0;
    } // Writes a bit to the stream. The specified bit must be 0 or 1.
    @Override
    public void write(int b) throws IOException
    {
    if (!(b == 0 || b == 1))
    throw new IllegalArgumentException("参数b必须是0或1。"); currentByte = currentByte << 1 | b;
    hasBits++;
    if (hasBits == 8)
    {
    output.write(currentByte);
    hasBits = 0;
    }
    } @Override
    public void close() throws IOException
    {
    // 如果没有写满一字节,就补0写满。
    while (hasBits != 0)
    write(0);
    output.close();
    }}
      

  6.   

    用 流的 缓冲类,bufferedwriter  buffferedreader