0
這是我的代碼,當我運行它時,它正確下載文件,但可能會在pc中使用很多內存。例如:我的內存是2.02 GB,當我運行應用程序時,我的內存達到了3GB,並減慢了我的電腦。 我使用wampserver爲我的網絡服務器和我的代碼,並設置http標題爲可能的對象,我donwnload文件正確,謝謝你的幫助。當我使用httpurlconnecion下載文件時,java會消耗大量內存內存?爲什麼?
private void downloadFile() {
try {
this.response = this.con.getInputStream();
this.bis = new BufferedInputStream(this.response, 1024 * 1024);
//int responseCode = this.con.getResponseCode();
this.responseContentSize = this.con.getContentLength();
//check kon bebin meghadare bargashti content ba on range ke to behesh gofti mosavi hast ya kheir
if (this.responseContentSize == (this.end_range - this.start_range) + 1) {
//fpointer = new RandomAccessFile(this.filePath, "rw");
//fpointer.seek(this.start_range);
byte buffer[] = new byte[MAX_BUFFER_SIZE];
//out = new FileOutputStream(this.filePath);
makeTmpFile();
out = new FileOutputStream(this.tmpdir + this.tmpFilename);
bos = new BufferedOutputStream(out, 1024 * 1024);
sharedDownloadStatus.setCell(this.threadIndex, STATUS, 1);//downloading
while (true) {
//int read = response.read(buffer, 0, this.MAX_BUFFER_SIZE);
int read = bis.read(buffer, 0, this.MAX_BUFFER_SIZE);
if (read == -1)
break;
//out.write(buffer, 0, read);
//fpointer.write(buffer, 0, read);
bos.write(buffer, 0, read);
downloadedBytes += read;
sharedDownloadStatus.setCell(this.threadIndex, DOWNLOADED, downloadedBytes);
}
if (bos != null)
bos.close();
if (out != null)
out.close();
if (fpointer != null)
fpointer.close();
if (bis != null)
bis.close();
if (response != null)
response.close();
sharedDownloadStatus.setCell(this.threadIndex, STATUS, 2);//finish
}
} catch (IOException e) {
sharedDownloadStatus.setCell(this.threadIndex, STATUS, 0);//error
log.setLog("func : downloadFile =>\n couldnt download file\n" + e.getMessage());
}
}
在實際的Android設備上運行該應用並驗證您的語句。我假設你使用仿真器的結果是在PC上看到RAM的跳躍。 –