I\'m working on a project for school, and I\'m implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I\'m gonna ha
As mentioned, URLConnection's getContentLengthLong() is your best bet, but it won't always give a definite length. That's because the HTTP protocol (and others that could be represented by a URLConnection) doesn't always convey the length.
In the case of HTTP, the length of dynamic content typically isn't known in advance—when the content-length header would normally be sent. Instead, another header, transfer-encoding, specifies that a "chunked" encoding is used. With chunked encoding, the length of the entire response is unspecified, and the response is sent back in pieces, where the size of each piece is specified. In practice, the server buffers output from the servlet. Whenever the buffer fills up, another chunk is sent. Using this mechanism, HTTP could actually start streaming a response of infinite length.
If a file is larger than 2 Gb, its size can't be represented as an int, so the older method, getContentLength() will return -1 in that case.