从java中的二进制文件中读取位串

时间:2016-09-25 22:24:04

标签: java arrays string binaryfiles

我有一串长度为128的位,我希望将其转换为字节数组,然后将其写入二进制文件,然后从二进制文件中读取并将字节数组转换为位字符串。这是我的代码(为简单起见,我使用长度为16的输入):

    String stest = "0001010010000010";
    //convert to byte array
    short a = Short.parseShort(stest, 2);
    ByteBuffer bytes = ByteBuffer.allocate(2).putShort(a);
    byte[] wbytes = bytes.array();

    System.out.println("Byte length: "+ wbytes.length);     
    System.out.println("Writing to binary file");
    try {
        FileOutputStream fos = new FileOutputStream("test.ai");
        fos.write(wbytes);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Reading from binary file");

    File inputFile = new File("test.ai");
    byte[] rdata = new byte[(int) inputFile.length()];
    //byte[] rdata = new byte[2];
    FileInputStream fis;
    String readstr = "";
    try {
        fis = new FileInputStream(inputFile);
        fis.read(rdata, 0, rdata.length);
        fis.close();
        for(int i=0; i<rdata.length; i++){
            Byte cb = new Byte(rdata[i]);
            readstr += Integer.toBinaryString(cb.intValue());
        }
        System.out.println("Read data from file: " + readstr);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但是,我从文件中读取的字符串不等于原始字符串。这是输出:

String: 0001010010000010
Byte length: 2
Writing to binary file
Reading from binary file
Read data from file: 1010011111111111111111111111110000010

1 个答案:

答案 0 :(得分:0)

我会开始选择我用于这两种情况的数据类型。让我们考虑一下,你选择字节。所以,写它很容易。

byte data[] = ... //your data
FileOutputStream fo = new FileOutputStream("test.ai");
fo.write(data);
fo.close();

现在,让我们从文件中读取字符串化数据。如您所知,1个字节是8位。因此,您需要从文件中读取8个字符,并将其转换为字节。所以,

FileInputStream fi = new FileInputStream("test2.ai"); // I assume this is different file
StringBuffer buf = new StringBuffer();
int b = fi.read();
int counter = 0;
ByteArrayOutputStream dataBuf = new ByteArrayOutputStream();
while (b != -1){
  buf.append((char)b);
  b = fi.read();
  counter++;
  if (counter%8 == 0){
    int i = Integer.parseInt(buf.toString(),2);
    byte b = (byte)(i & 0xff);
    dataBuf.write(b);
    buf.clear(0,buf.length());
  }
}
byte data[] = dataBuf.toByteArray();

我认为代码中的问题是将字符串转换为字节。你的出发点已经错了。您正在将数据转换为仅保留2个字节的short。但是,你说你的文件可以保留128位,即16字节。因此,您不应该尝试将整个文件转换为数据类型,如short,integer或long。你必须将每8位转换为字节。