Java Program to Get the Size of Given File in Bytes, KiloBytes and MegaBytes
The in-built File.length() method in java can be used to get file size in java. The length() function is a part of the File class in Java. This function returns the length of the file whose path was specified. If the file does not exist or some error happens then it returns 0.
Parameters: This method does not accept any parameter.
long len = file.length()
In the same way, exists() function is also a part of the File class in Java. This function determines whether the file or directory denoted by the abstract filename exists or not. The function returns true if the file whose path is given exists and if not then it returns false
Parameters: This method also does not accept any parameter.
Returns: True or False
This example shows how to get a file’s size in bytes by using file.exists() and file.length() method of File class.
bytes : 17,07,91,615 kilobytes : 1,66,788.686 megabytes : 162.8795766
Note: If you want file size in Gigabytes then again you have to divide mb value by 1024 and so on.
But Nowadays we can directly use File.size(path) after Java 7. In this we do not have to create file object we can directly find the size of the file.
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.