2016-04-11 52 views
1

我有一個文件,其中包含一個字符串後面跟着包含二進制數字編碼的字節。如何解碼包含java中字符串的文件中的字節?

Thisisastring. �J 

在我的代碼中,我嘗試忽略字符串,並專注於解碼由空格分隔的字節。當我運行代碼的結果似乎是正確的,除了第一個二進制數是關閉了很多。

StringBuffer buffer = new StringBuffer(); 
    File file = new File(arg); 
    FileInputStream in = new FileInputStream(file); 
    InputStreamReader isr = new InputStreamReader(in, "UTF8"); 
    Reader inn = new BufferedReader(isr); 
    int ch; 

    while ((ch = inn.read()) > -1){ 
     buffer.append((char)ch); 
    } 

    inn.close(); 

    String content = buffer.toString(); 
    String temp = new String(); 
    for(int i=0; i<content.length(); i++){ 
     temp += content.charAt(i); 
     if(content.charAt(i) == ' '){ 
      while(i != content.length()-1){ 
       i++; 
       byte b = (byte) content.charAt(i); 
       String x = Integer.toString(b & 0xFF, 2); 
       System.out.println(x); 
      } 
     } 
    } 

結果:

11111101 <- Why is only this one incorrect? 
11000 
1001010 
1011 

什麼是預期:

10010101 
00011000 
01001010 
1011 

回答

1

你不應該使用ReadersStrings二進制數據。

StringBuffer buffer = new StringBuffer(); 
File file = new File(arg); 
FileInputStream in = new FileInputStream(file); 
DataInputStream dis = new DataInputStream(new BufferedInputStream(in)); 
int ch; 

while ((ch = din.read()) > -1){ 
    buffer.append((char)ch); 
    if (ch == ' ') 
    { 
     // next byte is a binary value 
     byte b = din.readByte(); 
     String x = Integer.toString(b & 0xFF, 2); 
     System.out.println(x); 
    } 
} 
相關問題