How to get number of bytes that FileChannel.transferFrom wrote during it's writting

左心房为你撑大大i 提交于 2019-12-24 20:13:58

问题


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);

I debugged it and reaches the next line of code after the download is completed. How can I get the number of bytes that transferFrom() wrote during it's writing a file, to write it to a log or to the console?

Something like this

while (len = fch.getWriteBytes()) {
 System.out.println(len + " bytes : " + (len/total)*100 + "%");
}

Sorry for incomplete question.


回答1:


As describe in the API, you should write:

long bytes = fch.transferFrom(rbc, 0, Long.MAX_VALUE);

Then, bytes will contain the number of bytes actually transferred (note: this can be zero).

EDIT:

The transferFrom() is an OS-level function and therefore can't really be monitored directly from the FileChannelclass.

This SO answer seems to have a good approach - wrapping the ReadableByteChannel class to monitor the read() calls.



来源:https://stackoverflow.com/questions/19761896/how-to-get-number-of-bytes-that-filechannel-transferfrom-wrote-during-its-writt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!