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; System.out.println("File size in bytes: " + lSizeInBytes); |
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); } |