Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Size of file on the Internet using Java

  • Difficulty Level : Medium
  • Last Updated : 24 Mar, 2018

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: Class in Java

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.


// Java Program to calculate Size
// of a file on the Internet.
import java.math.BigInteger;
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(
        // create a connection
        HttpURLConnection conn;
            // open stream to get size of page
            conn = (HttpURLConnection)url.openConnection();
            // set request method.
            // get the input stream of process
            // 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");
        catch (Exception e)
            System.out.println("Connection failed");

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!