2012-07-12 77 views
0
private void readIncomingMessage() { 
    try { 
     StringBuilder builder = new StringBuilder(); 
     InputStream is = socket.getInputStream(); 
     int length = 1024; 
     byte[] array = new byte[length]; 
     int n = 0; 

     while ((n = is.read(array, n, 100)) != -1) { 
      builder.append(new String(array)); 

      if (checkIfComplete(builder.toString())) { 
       buildListItems(builder.toString(), null); 
       builder = new StringBuilder(); 
      } 
     } 

    } catch (IOException e) { 
     Log.e("TCPclient", "Something went wrong while reading the socket"); 
    } 
} 

嗨,,並添加到StringBuilder的

我想讀每100個字節塊流,這些字節轉換爲字符串,比看看是否有適合的字符串一定的條件。

但是,當我調試時,我看到該構建器的計數爲3072.
而且我看到一個像(text,,,,,,,text,,,,,,text)
我該如何將文本添加到stringbuilder中?

THX :)

private void readIncomingMessage() { 
    try { 
     StringBuilder builder = new StringBuilder(); 
     InputStream is = socket.getInputStream(); 
     int length = 100; 
     byte[] array = new byte[length]; 
     int n = 0; 

     while ((n = is.read(array, 0, length)) != -1) { 
      builder.append(new String(array, 0, n)); 

      if (checkIfComplete(builder.toString())) { 
       buildListItems(builder.toString(), null); 
       builder = new StringBuilder(); 
      } 
     } 

    } catch (IOException e) { 
     Log.e("TCPclient", "Something went wrong while reading the socket"); 
    } 
} 

該解決方案並獲得成功對我來說。 此解決方案的任何缺點?

+0

這並不一定是連續的100個字節的任何特定塊將成功地轉化爲'String'的情況下... – 2012-07-12 15:04:12

回答

2

2個問題:

  1. 你需要轉換的字節字符串時使用'n'值。具體來說,使用此String構造函數String(byte[] bytes, int offset, int length)
  2. 將字節轉換爲任意邊界上的字符串時(如您所做的那樣),可能會損壞多字節字符。如果'is'和從中讀取字符,你最好把InputStreamReader放在最上面。
1

欲瞭解更多信息,請閱讀文檔read(byte[], int, int)new String(byte[])new String(byte[], int, int)

ň將持有讀取最後一次讀操作的字節數 - 而不是數讀取的字節。如果您只想一次讀取多達100個字節,則不需要1024字節的數組,而是100個字節。從字節數組創建字符串時,它會使用整個數組(即使只有一半可以通過讀取來填充),除非您告訴它要使用的數組的哪一部分。像這樣的東西應該工作,但仍有改進,你可以做:

private void readIncomingMessage() { 
    try { 
    StringBuilder builder = new StringBuilder(); 
    InputStream is = socket.getInputStream(); 
    int length = 100; 
    byte[] array = new byte[length]; 
    int pos = 0; 
    int n = 0; 

    while (pos != length && ((n = is.read(array, pos, length-pos)) != -1)) { 
     builder.append(new String(array, pos, n)); 
     pos += n; 
     if (checkIfComplete(builder.toString())) { 
      buildListItems(builder.toString(), null); 
      builder = new StringBuilder(); 
      pos = 0; 
     } 
    } 

} catch (IOException e) { 
    Log.e("TCPclient", "Something went wrong while reading the socket"); 
} 

}

+0

當然,也有多字節字符。您可能想使用'InputStreamReader#read(char [],int,int)'代替。 – 2012-07-12 15:15:36

相關問題