How to calculate the amount of data downloaded and the total data to be downloaded in Java? E.G. 12kb/130kb...110kb/130kb
Asked
Active
Viewed 1,959 times
2 Answers
2
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.

Bozho
- 588,226
- 146
- 1,060
- 1,140
-
Just make sure that the Content-Length header is set. I have found if you are calling custom servlets you need to set the header in the response. – Koekiebox May 10 '11 at 10:34
-
@Bozho I have the same problem in here http://stackoverflow.com/questions/15349296/implement-pause-resume-in-file-downloading, Can you take a look? – Ali Mar 14 '13 at 18:53
2
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.

Alex Gitelman
- 24,429
- 7
- 52
- 49