Remote File Size

Remote File Size

How can I discover the size of a remote file stored on an HTTP server?

The HTTP protocol supports the transfer of extra information about thecontent referenced by a URL. This information is stored in the HTTPheader fields. The Content-Length header provides the size of theobject referenced by the URL. Not all web servers will provide thisinformation, so you should not develop your client code to rely on itsavailability.

The class provides access to any arbitrary HTTPheader field through the getHeaderField() method, which will returnthe value of header as a string. Two other methods,getHeaderFieldDate() and getHeaderFieldInt(), will return the valuesof fields containing dates or integers as Date and int typesrespectively. They are convenience methods that save you the troubleof parsing the header field. URLConnection also provides conveniencemethods for accessing commonly used header fields, such asLast-Modified, Content-Type, and, yes, even Content-Length. The valueof the Content-Length header is directly returned as an integer bygetContentLength(). If the header value does not exist, the methodreturns -1.

Before querying the value of a header, you first need to establish aconnection. The normal way to do this is to create a URL instancethat points to the object you want to access, and then create aURLConnection with openConnection(). The following exampledemonstrates how to open a URLConnection and obtain the byte length ofthe content referenced by the URL.

import*;import*;public final class URLFileSize {  public static final void main(String[] args) {    URL url;    URLConnection connection;    int fileSize;    if(args.length != 1) {      System.err.println("Usage: URLFileSize ");      return;    }    try {      url = new URL(args[0]);      connection = url.openConnection();      fileSize = connection.getContentLength();      if(fileSize 


Share the Post: