Skip to content
Related Articles
Open in App
Not now

Related Articles

Java Program to Get the Size of Given File in Bytes, KiloBytes and MegaBytes

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 09 Mar, 2021
Improve Article
Save Article

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.


// Simple Java Program find  the size of the file
public class GFG {
    public static void main(String[] args)
        // create file object enter the path of
        // the file for which size is to be found
        File file = new File("/home/user/GFG.txt");
        if (file.exists()) {
            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            // converting file size to bytes to kb
            double megabytes = (kilobytes / 1024);
            // converting file size tolb to mb
            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.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!