Find the file size using Java code (Bytes, KB, MB and GB)

 


There are multiple instances when you want to find out or display the size of a file. It can be for filtering out files of certain file sizes or limit the upload size of a file. For that purpose, we'll have to find out the file size. 

We'll utilize an inbuilt function which returns the size in bytes, and we'll write our own functions to find out file sizes in KB, MB and GB i.e. KiloBytes, MegaBytes, and GigaBytes.

The function that we'll be using is file.length().

Now for the implementation. If you want to display the file size, the String format is more suitable. 

/**
 * Get File size in GB
 * @author computengine.com
 * @param file
 * @return
 */
public static String getFileSizeGigaBytes(File file) {
	return Double.toString((double) file.length() / (1024 * 1024 * 1024));
}

/**
 * Get File size in MB
 * @author computengine.com
 * @param file
 * @return
 */
public static String getFileSizeMegaBytes(File file) {
	return Double.toString((double) file.length() / (1024 * 1024));
}


/**
 * Get File size in KB
 * @author computengine.com
 * @param file
 * @return
 */
public static String getFileSizeKiloBytes(File file) {
	return Double.toString((double) file.length() / 1024);
}


/**
 * Get File size in Bytes
 * @author computengine.com
 * @param file
 * @return
 */
public static String getFileSizeBytes(File file) {
	return Double.toString((double) file.length());
}


In case you want to compare file sizes, the double format is more suitable. 


/**
 * Get File size in GB
 * @author computengine.com
 * @param file
 * @return
 */
public static double getFileSizeGigaBytes(File file) {
	return ((double) file.length() / (1024 * 1024 * 1024));
}

/**
 * Get File size in MB
 * @author computengine.com
 * @param file
 * @return
 */
public static double getFileSizeMegaBytes(File file) {
	return ((double) file.length() / (1024 * 1024));
}


/**
 * Get File size in KB
 * @author computengine.com
 * @param file
 * @return
 */
public static double getFileSizeKiloBytes(File file) {
	return ((double) file.length() / 1024);
}


/**
 * Get File size in Bytes
 * @author computengine.com
 * @param file
 * @return
 */
public static double getFileSizeBytes(File file) {
	return ((double) file.length());
}


Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on FacebookTwitterTumblr.

Comments

Popular posts from this blog

Calculate Your CTC Salary Hike Percentage - Online Calculator to find your New Salary

Find the Longest Streak of 1's in a Binary Array using Java Code

Java Program to read Excel File and Load into Array

Java Program to Read a Properties file and return a Property Value

4 ways to add New Line Character to a String in Java