gpt4 book ai didi

没有close()方法的Java中断输入流

转载 作者:可可西里 更新时间:2023-11-01 16:40:49 32 4
gpt4 key购买 nike

所以,我有一段代码可以连接到服务器并以 2mb block 的形式下载大约 2gb 的内容。所有这些都是在线程中完成的。有时我需要停止线程,因为主线程中发生了不同的错误,或者我想关闭应用程序。我的问题是我无法关闭连接的 InputStream。每次我调用 close() 方法时,InputStream 都会消耗服务器发送的整个 2gb。有没有办法在不消耗服务器发送的全部内容的情况下关闭 InputStream?

fos.getChannel().transferFrom(Channels.newChannel(res.getEntity().getContent()), bytes_read, CHUNK_SIZE);
res.getEntity().getContent().close();

res.getEntity().getContent()返回从连接创建的 InputStream。

res 是一个 apache httpResponse。

fos 是我要保存响应内容的FileOutputStream。

编辑:线程的运行方法

CHUNK_SIZE: int: 2mb 字节

@Override
public void run() {
int expectedCode;
do{
try {
client = HttpClients.createDefault();

HttpGet req = new HttpGet(url.toString());
HttpResponse res = client.execute(req);

if (res.getStatusLine().getStatusCode() == 200) {
while(running){
fos.getChannel().transferFrom(Channels.newChannel(res.getEntity().getContent()), bytes_read, CHUNK_SIZE);
}
} else {
log.error(Languages.getString("Download.2") + expectedCode); //$NON-NLS-1$
}
} catch (Exception ex) {
log.error(ex);
} finally{
try{
rbc.close();
} catch(Exception ex){
log.error(ex);
}
}
}while(!isFinished() && running);
try{
rbc.close();
fos.close();
client.close();
} catch(Exception ex){
log.error(ex);
}
}

最佳答案

Apache HttpClient 的底层实现使用 ContentLengthInputStream 来保持响应。如 ContentLengthInputStream 中所述,.close() 方法实际上从未关闭流,而是读取所有剩余字节,直到达到 Content-Length。

解决方案:不要调用 res.getEntity().getContent().close(),而是尝试 res.close()req.abort( )

关于没有close()方法的Java中断输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40947622/

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