Get File Size in JAVA

How to get File Size in JAVA?

In this Example we are going to learn how to get file size in Java

File class has a method length() will return size of file

import java.io.File;
 public class PrintFileSize {
  public static void main(String[] args) {
      String strFilePath = "E:/java/text.txt";
        //File object denoting the file
        File file = new File(strFilePath);
        if(file.exists())
        {
            /*
            * To get the file size, use length method of
            * the File class. This method returns size of file
            * in bytes.
            */
           long lSizeInBytes = file.length();

           System.out.println("File size in bytes: " + lSizeInBytes);
        }else
        {
            System.out.println("File Not exists " );
        }
     }
}

In the above example we are checking first file exist or not, if file not exists it return "File Not exists" else print size of file

output

File size in bytes: 68 

 

Get File Size in KB, MB, GB in JAVA

if(file.exists()){

           long lSizeInBytes = file.length();

            System.out.println("File size in bytes: " + lSizeInBytes);

           //divide bytes by 1024 to get size in kilobytes

            double dSizeInKB = lSizeInBytes/1024;

            System.out.println("File size in kilobytes (KB): " + dSizeInKB);

         //divide kilobytes by 1024 to get size in megabytes

            double dSizeInMB = dSizeInKB/1024;

            System.out.println("File size in megabytes (MB): " + dSizeInMB);

           //divide megabytes by 1024 to get size in gigabytes

            double dSizeInGB = dSizeInMB/1024;

            System.out.println("File size in gigabytes (GB): " + dSizeInGB);

 //divide gigabytes by 1024 to get size in terabytes

            double dSizeInTB = dSizeInGB/1024;

            System.out.println("File size in terabytes (TB): " + dSizeInTB);

 }

 


Subscribe For Daily Updates

JAVA File IO examples

JAVA Date & Time Progamming Examples

JAVA Collections

Flutter Questions
Android Questions