2012-09-02 10 views
2

이것은 자주 묻는 질문 일 텐데 아직 정답을 찾을 수 없습니다.HTTPConnection을 통해 큰 파일 다운로드 - Java Applet

글쎄, 나는 다음과 같은 코드를 가지고 :

java.net.URL url = new java.net.URL(built); 
java.net.HttpURLConnection con = (HttpURLConnection)url.openConnection(); 

if (con.getResponseCode() != 200) { 
    // error handle here!; 
    continue; 
} 

// begin to download the file 
int file_size = con.getContentLength(); 

FileOutputStream stream = new FileOutputStream(m_WorkingDir + "/" + getFilenameWithPath(i)); 
InputStream remoteStream = con.getInputStream(); 

int chunks = (int) Math.ceil((float)file_size/(float)CHUNK_SIZE); 

// download each chunk 
byte[] temp = new byte[CHUNK_SIZE]; 
for(int a = 0; a < chunks; a++) { 
    // calculate chunk size 
    int chunk_size = CHUNK_SIZE; 

    if(a == chunks-1) { 
     // last chunk 
     chunk_size = file_size - a * CHUNK_SIZE; 
     System.out.println("Download last chunk : " + chunk_size); 
    } 

    // download chunk 
    int bytes = remoteStream.read(temp, 0, chunk_size); 
    stream.write(temp, 0 ,chunk_size); // save to local filesystem 
} 

stream.close(); 
remoteStream.close(); 
con.disconnect(); 

이 코드는 단순히 파일 청크 다운로드 "해야"..를하지만 점은 제대로하지 않는다는 점입니다. 내가 코드를 디버깅하고 그것은 ~ 10 청크 올바르게 읽었지만 그 chunk_size의 절반처럼 읽지 않는 경우에도 그 마지막 덩어리가 아니라 다음 -1까지 반환합니다 (int a ...) 끝내다.

내게는 InputStream이 EOF라고 생각하는 것 같습니다. 그리고 예. HTTP 연결을 일반적인 브라우저를 통해 테스트했는데 제대로 작동했습니다.

CHUNK_SIZE에 대한 여러 설정으로 코드를 테스트했지만 항상 동일한 결과가있었습니다. 자바는 말한다 때문에

을 다운로드 할 파일은, 10 ~ 메가 바이트 ..

답변

3

당신은 전체 청크 크기를 다운로드 할 수있는 프로그램을 가정하고 있지만이 경우하지 않을 수 있습니다 약 : -

len (CHUNK_SIZE) 바이트만큼 읽으려고 시도하지만 더 작은 수 을 읽을 수 있습니다. 아마도 0 일 수 있습니다.

이 작동 할 수 있습니다 : -

byte[] temp = new byte[CHUNK_SIZE]; 
int bytes = 0; 
for(int a = 0; a < chunks; a++) { 
    bytes =remoteStream.read(temp, 0, CHUNK_SIZE); 
    if(bytes == -1) { 
     System.out.println("Downloaded last chunk : Terminating "); 
     break; 
    } 
    stream.write(temp, 0 ,bytes); 
}