Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Mar 6, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 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 ");

    try {
      url = new URL(args[0]);

      connection = url.openConnection();
      fileSize = connection.getContentLength();

      if(fileSize < 0)
	System.err.println("Could not determine file size.");
	System.out.println(args[0] + "\nSize: " + fileSize);

    } catch(IOException e) {
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date