Java Program to Get the Size of Given File in Bytes, KiloBytes and MegaBytes
Last Updated :
09 Mar, 2021
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.
Syntax:
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
Syntax:
file.exists()
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.
Java
import java.io.File;
public class GFG {
public static void main(String[] args)
{
File file = new File( "/home/user/GFG.txt" );
if (file.exists()) {
double bytes = file.length();
double kilobytes = (bytes / 1024 );
double megabytes = (kilobytes / 1024 );
double gigabytes = (megabytes / 1024 );
System.out.println( "bytes : " + bytes);
System.out.println( "kilobytes : " + kilobytes);
System.out.println( "megabytes : " + megabytes);
}
else {
System.out.println( "File does not exists!" );
}
}
}
|
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...