How to calculate the file size downloaded and the total data to be downloaded in Java?
How to calculate the amount of data downloaded and the total data to b开发者_Python百科e downloaded in Java? E.G. 12kb/130kb...110kb/130kb
If you mean downloading files via http using URLConnection
, then you can
- get the
Content-Length
response header to get the total size. This is done viaconnection.getContentLength()
- to get the already downloaded amount, just count the bytes you have processed from the stream.
To get amount of data that has been downloaded you can use CountingInputStream from Apache Commons IO. See http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CountingInputStream.html Wrap your stream in it.
To get total length you need to use information from the server. For example, Content-Length header as previously mentioned. But it only works for http. It may not always be possible in generic case.
精彩评论