devxlogo

Remote File Size

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 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 java.net.URLConection 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 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] + "
Size: " + fileSize);      connection.getInputStream().close();    } catch(IOException e) {      e.printStackTrace();    }  }}
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist