Pages

Wednesday, June 19, 2013

Remote File Size using Java

Remote File Size

Question:
How can I discover the size of a remote file stored on an HTTP server? Answer:
The HTTP protocol supports the transfer of extra information about the content referenced by a URL. This information is stored in the HTTP header fields. The Content-Length header provides the size of the object referenced by the URL. Not all web servers will provide this information, so you should not develop your client code to rely on its availability.

The java.net.URLConection class provides access to any arbitrary HTTP header field through the getHeaderField() method, which will return the value of header as a string. Two other methods, getHeaderFieldDate() and getHeaderFieldInt(), will return the values of fields containing dates or integers as Date and int types respectively. They are convenience methods that save you the trouble of parsing the header field. URLConnection also provides convenience methods for accessing commonly used header fields, such as Last-Modified, Content-Type, and, yes, even Content-Length. The value of the Content-Length header is directly returned as an integer by getContentLength(). If the header value does not exist, the method returns -1.

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

import java.io.*;
import java.net.*;

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 < 0)
 System.err.println("Could not determine file size.");
      else
 System.out.println(args[0] + "\nSize: " + fileSize);

      connection.getInputStream().close();
    } catch(IOException e) {
      e.printStackTrace();
    }
  }
}

No comments:

Post a Comment