2013-08-17 31 views
0

我有一個讀取器接收流(ByteArrayInputStream)的消息數據包。
每個數據包包含由英文字符後跟二進制數字組成的數據。查找流中最後一個英文字符的位置

adghfjiyromn1000101010100...... 

什麼是最有效的方法來複制(而不是去掉)作爲一個序列這個流的字符。 因此,上述數據包的預期產出將是(不修改原始數據流):

adghfjiyromn 

我不僅關心邏輯,而且確切的流處理例程使用;考慮到讀者會假設每秒讀取約3-4個數據包。
這也將有助於提供爲什麼我們更喜歡特定數據類型(byte [],char []或string)來解決這個問題的理由。

+1

請給一個輸入和預期的輸出。 –

回答

0

我認爲最好的辦法是按字節讀取字節ByteArrayInputStream的:

ByteArrayInputStream msg = ... 
int c; 
String s; 
while ((c = msg.read())!= -1) { 
    char x = (char) c; 
    if (x=='1' || x=='0') break; 
    s += x; 
} 
0

我認爲它的最佳方式:

1 - 轉換你的ByteArrayInputStream進行到字符串(或StringBuffer的) 2-找到0或1 3使用字符串的第一個索引(0,FIRST_INDEX)

0

你:每個數據包中包含的數據包括英文字符,隨後是二進制數字。 Me:數據在bytearrayinputstream中,因此所有內容都是二進制的。 您的1000101010100 ......是字符'1'&'0'?

如果是

ByteArrayInputStream msg = //whatever 
     int totalBytes = msg.available(); 
     int c; 
     while ((c = msg.read())!= -1) { 
      char x = (char) c; 
      if (x=='1' || x=='0') break; 
     } 
     int currentPos = msg.available() + 1; //you need to unread the 1st 0 or 1 
     System.out.println("Position = "+(totalBytes-currentPos)); 
相關問題