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 Hike Percentage

Java Program to Find a List of Prime Numbers (Step by Step)

Java Program to check Palindrome

What is my IP Address - How to find your IP address on Local Network using Command Prompt, and External Network using JavaScript Code

Reduce Server Load from Dynamic Page Search - Create a Dynamic JavaScript based Table filter