【问题标题】:Reading bit string from binary file in java从java中的二进制文件中读取位串
【发布时间】:2016-09-25 22:24:03
【问题描述】:

我有一个长度为 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

【问题讨论】:

  • 对 fis.read(rdata, 0, rdata.length) 的调用返回实际读取的字符数,您应该在 for 循环中使用该数字而不是 rdata.length。

标签: java arrays string binaryfiles


【解决方案1】:

我会开始选择用于这两种情况的数据类型。让我们想想,你选择字节。因此,编写它非常容易。

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 个字节的短数据。但是,您说您的文件可以保留 128 位,即 16 字节。因此,您不应尝试将整个文件转换为一种数据类型,如短整型或长整型。您必须将每 8 位转换为字节。

【讨论】:

  • 我不记得实际功能。但是,目的是清理缓冲区。方法名称可能是“干净的”。或者你可以使用 buf = new StringBuffer();
猜你喜欢
  • 2015-07-27
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 2018-01-16
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多