Friday, October 10, 2025
HomeLanguagesJavaSize of file on the Internet using Java

Size of file on the Internet using Java

To get the size of file from server first you need to connect to the server using URL and HttpURLConnection Class. To get the size of file we use getContentLength() method. As the size of file can be too large we use BigInteger class. You cannot use integer datatype as it can generate an error in case the size of file is greater than 2Gb.
To know more about BigInteger class refer link: BigInteger class in Java
For HttpURLConnection refer link: Java.net.HttpURLConnection Class in Java

Java




// Java Program to calculate Size
// of a file on the Internet.
import java.math.BigInteger;
import java.net.URL;
import java.net.HttpURLConnection;
  
public class SizeFile {
      
    public static void main(String args[]) throws Exception
    {
        BigInteger size = new BigInteger("1");
  
        // get the url of web page
        URL url = new URL(
            "https://media.geeksforgeeks.org/wp-content/uploads/GATE.pdf");
      
        // create a connection
        HttpURLConnection conn;
        try
        {
                  
            // open stream to get size of page
            conn = (HttpURLConnection)url.openConnection();
              
            // set request method.
            conn.setRequestMethod("HEAD");
              
            // get the input stream of process
            conn.getInputStream();
              
            // store size of file
            size = BigInteger.valueOf(conn.getContentLength());
              
            // print the size of downloaded file
            System.out.println("The Size of file is:" +
                                       size + " bytes");
            conn.getInputStream().close();
        }
        catch (Exception e)
        {
            System.out.println("Connection failed");
        }
    }
}


RELATED ARTICLES

Most Popular

Dominic
32349 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6715 POSTS0 COMMENTS
Nicole Veronica
11878 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6837 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS