2012-05-11 75 views
2

我明顯不知道問題出在哪裏!首先我要求客戶端發送他要發送的byte[]的長度,然後我讀取其長度這個。從InputStream讀取到byte []拋出IndexOutOfBoundsException

int i = 323292; // length of incoming Byte[] 
byte[] b = new byte[i]; 
int readBytes=inputStream.read(b,0,b.length); 

但它總是讀readBytes小於i。我相信客戶發送整個byte[]

我試圖把它放在一個循環內,直到我讀取的字節總數爲i,但我總是在第二次迭代後得到IndexOutOfBoundsException!這裏是代碼

boolean flag = true; 
int i = 323292; 
int threshold = 0; 
byte[] b = new byte[i]; 
int read = 0; 
while (flag) { 
    if (threshold < i) { 
     System.out.println(threshold); 
     try { 
      read = inputStreamFromClient.read(b, threshold, b.length); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     threshold = threshold + read; 
    } else { 
     flag = false; 
    } 
} 

AnyIdeas?

+1

你真的應該使用Commons IO包中的一個給自己節省一些編碼時間和不必要的複雜性:HTTP://commons.apache。 org/io/api-release/org/apache/commons/io/IOUtils.html#toByteArray(java.io.InputStream) – grahamrb

+0

感謝您的幫助我會檢查它! –

+0

這個簡單的任務不需要第三方軟件。參見'DataInputStream.readFully()'。 – EJP

回答

7

此:

read = inputStreamFromClient.read(b, threshold, b.length); 

應該是:

read = inputStreamFromClient.read(b, threshold, b.length - threshold); 
+0

你是一個拯救生命的人!謝謝! –

+0

而'threshold'通常被稱爲'offset'。請參閱API文檔。 – EJP

相關問題