将数字存储为文件中的二进制

时间:2011-11-28 07:07:53

标签: java file ascii store

我的数据在我的文件中写为ASCII码。例如,“9”被存储为两个字节57,即总共8位。

我希望通过将这些数字存储为二进制值来优化存储,例如0-9的数字,仅使用4位存储。

任何帮助?!

4 个答案:

答案 0 :(得分:1)

这个怎么样? 0 => 0000 1 => 0001 2 => 0010 3 => 0011 4 => 0100 5 => 0101 6 => 0110 7 => 0111 8 => 1000 9 => 1001

答案 1 :(得分:1)

你可以像那样写二进制文件

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class Bin {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new  FileOutputStream("\\test.bin");
        String digits="12345";
        char[] chars = digits.toCharArray();
        for ( int i = 0 ; i < chars.length ; i+= 2 ) {
            byte b1 = (byte) (chars[i] - (byte) '0');
            byte b2 = (byte) (i < chars.length-1 ? chars[i+1] - (byte) '0' : 0xf);
            fos.write((byte) ((b1 << 4) | b2 ));
        }
        fos.close();
        FileInputStream fis = new FileInputStream("\\test.bin");
        StringBuffer result = new StringBuffer();
        byte[] buf = new byte[100];
        int read = fis.read(buf);
        ByteArrayInputStream bais = new ByteArrayInputStream(buf);
        for ( int i = 0 ; i < read ; i++ ) {
            byte both = (byte) bais.read();
            byte b1 = (byte) ((both >> 4 ) & 0xf);
            byte b2 = (byte) (both  & 0xf) ;
            result.append( Character.forDigit(b1, 10));
            if ( b2 != 0xf ) {
                result.append(Character.forDigit(b2,10));
            }
        }
        System.out.println(result.toString());
    }
}

但我怀疑这会非常有用

答案 2 :(得分:1)

我会坚持使用标准的DataOutputStream,它可以用可移植的方式将原始类型写入输出

它有writeLongwriteInt。使用这些方法,您可以写出您的数据,然后使用DataInputStreamreadLongreadInt加载数据。

如果这不够紧凑,您可以稍后使用任何压缩库对其进行压缩。

答案 3 :(得分:0)

如果你写字符,每个字符需要1字节。您必须编写二进制或布尔数据。您可以表示5 =&gt; 0101,但如果您将0101作为字符写入,则需要4字节,如果您编写二进制或布尔值,则需要使用位。

相关问题