The size of files in Java can be obtained using the File class. The in-built function of ‘fileName.length()’ is used to find size of file in Bytes. The directory may contain ‘N’ number of files, for calculating the size of the directory summation of the size of all the files is required.
length() method in the object of the file class is returning the file size in long(datatype) format. The file size is in a unit of Byte.
Return Type: long
java.io.File file = new java.io.File("file_name.txt"); file.length();
- If the file exists then the function return the size of the file
- Else the function returns null.
However, the size of the file can be display in Mega, Kilo units using unit conversion.
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.