0

How to calculate the amount of data downloaded and the total data to be downloaded in Java? E.G. 12kb/130kb...110kb/130kb

Andrew Thompson
  • 166,747
  • 40
  • 210
  • 420
Jitesh
  • 284
  • 1
  • 6
  • 19

2 Answers2

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 via connection.getContentLength()
  • to get the already downloaded amount, just count the bytes you have processed from the stream.
Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
  • 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? – NullPointer 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
  • 23,919
  • 7
  • 50
  • 49