2016-12-03 47 views
2

因此,我有一段代码连接到服务器,并以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); 
    } 
} 
+0

所以每当你调用.close(),线程被阻塞,直到所有数据的2Gb已经tranfered? – ntahoang

+0

.close()方法阻塞线程并接收直到所有2GB都被读取,但它不传输任何字节,它只会清除输入流 –

+0

也许.close()不是罪魁祸首,而是围绕它的代码。 InputStream的实际实现是什么?你可以发布一些附加代码吗? – ntahoang

回答

0

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

解决方案:与其说res.getEntity().getContent().close(),尽量res.close()req.abort()

+0

'res.close()'解决了这个问题。谢谢 –