2016-09-25 120 views
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 

回答

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個字節的短數據。但是,你說你的文件可以保持128位,即16個字節。所以,你不應該嘗試將整個文件轉換爲數據類型,比如short,integer或long。你必須將每8位轉換爲字節。

+0

buf.clear方法不存在!!!!!!!!!! –

+0

我不記得實際的功能。但是,目的是清理緩衝區。方法名稱可能是「乾淨」的。或者你可以使用buf = new StringBuffer(); – Adem

相關問題