我正在使用apache httpclient和filechannel.transferFrom从Internet下载文件它适用于小文件但是对于大文件它永远不会完成。对于727.7 mb文件大约300 mb下载并且所有线程都已完成,即从函数传输没有复制所有字节。
HttpGet get = new HttpGet(uri);
// Range header for defining which segment of file we want to receive.
String byteRange = intialState.get(name) + "-" + finalState.get(name);
get.setHeader("Range", "bytes=" + byteRange);
try (CloseableHttpResponse response = client.execute(get);
ReadableByteChannel inputChannel = Channels.newChannel(
response.getEntity().getContent())) {
while (intialState.get(name) < finalState.get(name)
&& currentState.get() == 1 && delta != 0) {
delta = fileChannel.transferFrom(inputChannel,
intialState.get(name), 8192);
intialState.addAndGet(name, delta);
bytesDone.addAndGet(delta);
}
}
如果我删除delta!= 0,则线程永远不会结束,因为输入通道变空并且initialstate.get(name)&lt; finalstate.get(name)仍然有效,即写入的字节小于文件大小。那么如何解决这个问题呢?如何使filechannel.transferFrom从inputchannel读取所有字节?如果这不可能那么任何替代方案?我只是想以一种有效的方式以最快的速度下载文件。