File sizes are usually represented in bytes, but for better understanding, we may often need to display the file size in more human-readable units like MB, KB & GB. In this article, we will see how to get the size of a file in MB, KB and GB in java.
In Java’s IO library, we have a class called File which provides several methods to obtain file-releated information such as size etc. To get the file size in bytes, we can use the length()
method of the File
class. To convert the file size to MB, KB, or GB, we will perform simple arithmetic operations.
Get the file size:
Let us first import the File class and create a File
object representing the file whose size you want to obtain and then use the length()
method to get the file size in bytes.
import java.io.File;
File file = new File("path/to/your/file.ext");
long fileSizeBytes = file.length();
Converting the file size
To convert the file size from bytes to MB, KB, or GB, we can perform the following conversions:
- MB (Megabytes): Divide the file size in bytes by 1,048,576 (1024 * 1024).
- KB (Kilobytes): Divide the file size in bytes by 1,024 (1024).
- GB (Gigabytes): Divide the file size in bytes by 1,073,741,824 (1024 * 1024 * 1024).
Following is an example of how to convert the file size and display it in KB, MB & GB.
public class FileSizeExample {
public static void main(String[] args) {
File file = new File("path/to/your/file.ext");
long fileSizeBytes = file.length();
double fileSizeKB = (double) fileSizeBytes / 1024;
double fileSizeMB = fileSizeKB / 1024;
double fileSizeGB = fileSizeMB / 1024;
System.out.println("File Size: " + fileSizeBytes + " bytes");
System.out.println("File Size: " + fileSizeKB + " KB");
System.out.println("File Size: " + fileSizeMB + " MB");
System.out.println("File Size: " + fileSizeGB + " GB");
}
}