gpt4 book ai didi

当我使用 httpurlconnection 下载文件时,java 消耗大量内存?为什么?

转载 作者:行者123 更新时间:2023-12-01 12:53:12 33 4
gpt4 key购买 nike

这是我的代码,当我运行它时,它会正确下载文件,但可能会在电脑上使用大量内存。例如:我的 RAM 是 2.02 GB,当我运行应用程序时,我的 RAM 会上升到 3GB,从而降低我的电脑速度。我使用 wampserver 作为我的网络服务器和我的代码,并将 http header 设置为可能的对象,我正确下载文件,感谢您的帮助。

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());
}

}

最佳答案

您不需要兆字节缓冲区,但主要问题是 HttpURLConnection 将缓冲所有内容,除非固定长度或分块传输模式生效,这是由服务器而不是客户端控制的。

关于当我使用 httpurlconnection 下载文件时,java 消耗大量内存?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24057779/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com