2012-05-11 2 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[]을 보내는 것이 틀림 없습니다.

루프에 넣으려고했는데, 총 바이트 수를 읽을 때까지 읽었지만, 두 번째 반복 이후에는 항상 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

당신은 정말 자신에게 약간의 코딩 시간과 불필요한 복잡성을 저장 커먼즈 IO 패키지 중 하나를 사용해야합니다. 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); 

가되어야합니다 : HTTP : //commons.apache

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

당신은 생명의 은인입니다! 감사! –

+0

그리고 'threshold'는 일반적으로 'offset'이라고합니다. API 설명서를 참조하십시오. – EJP

관련 문제