0
我有一個長度爲128的位的字符串,我想將其轉換爲字節數組,然後將其寫入二進制文件,然後從二進制文件中讀取並將字節數組轉換爲位字符串。這是我的代碼(我用長度爲16的爲了簡化輸入):從java中的二進制文件讀取位字符串
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
buf.clear方法不存在!!!!!!!!!! –
我不記得實際的功能。但是,目的是清理緩衝區。方法名稱可能是「乾淨」的。或者你可以使用buf = new StringBuffer(); – Adem