因此,我有一段代码连接到服务器,并以2mb的块下载大约2GB的内容。所有这些都是在一个线程中完成的。有时我需要停止线程,因为在主线程中发生了不同的错误,或者我想关闭应用程序。我的问题是,我无法关闭连接的InputStream。每次我调用close()
方法时,InputStream消耗服务器发送的整个2gb。 有没有办法关闭一个InputStream而不消耗服务器发送的全部内容?没有关闭()方法的Java中断输入流
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);
}
}
所以每当你调用.close(),线程被阻塞,直到所有数据的2Gb已经tranfered? – ntahoang
.close()方法阻塞线程并接收直到所有2GB都被读取,但它不传输任何字节,它只会清除输入流 –
也许.close()不是罪魁祸首,而是围绕它的代码。 InputStream的实际实现是什么?你可以发布一些附加代码吗? – ntahoang