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( // 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"); } } } |
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Checking Internet Connectivity using Java
- Java.io.File Class in Java
- File Permissions in Java
- Delete a file using Java
- Java | Renaming a file
- Java Class File
- Check if a File is hidden in Java
- Java | Appending String to a File
- Reading a CSV file in Java using OpenCSV
- Writing a CSV file in Java using OpenCSV
- Myth about the file name and class name in Java
- Copying file using FileStreams in Java
- Moving a file from one directory to another using Java
- How to play an Audio file using Java
- How to run java class file which is in different directory?
- Java program to delete certain text from a file
- File renameTo() method in Java with examples
- File getAbsolutePath() method in Java with Examples
- File setReadable() function in Java with Examples
- File canExecute() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

