HttpURLConnection conn = (HttpURLConnection) url.openConnection();
ReadableByteChannel rbc = Channels.newChannel(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(fileName);
FileChannel fch = fos.getChannel();
fch.transferFrom(rbc, 0, Long.MAX_VALUE);
我调试了一下,下载完成后到达下一行代码。
如何获取 transferFrom()
在写入文件期间写入的字节数,并将其写入日志或控制台?
类似这样的事情
while (len = fch.getWriteBytes()) {
System.out.println(len + " bytes : " + (len/total)*100 + "%");
}
抱歉问题不完整。
最佳答案
如 API 中所述,你应该写:
long bytes = fch.transferFrom(rbc, 0, Long.MAX_VALUE);
然后,bytes
将包含实际传输的字节数(注意:这可以为零)。
编辑:
transferFrom()
是操作系统级函数,因此无法真正从 FileChannel
类直接进行监控。
This SO answer似乎有一个很好的方法 - 包装 ReadableByteChannel 类来监视 read() 调用。
关于java - 如何获取 FileChannel.transferFrom 在写入过程中写入的字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19761896/