【发布时间】: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