Showing posts from October, 2021

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  * @param file  * @return  */ public static String getFileSizeGigaBytes ( File file ) { return Double . toString ( ( double ) file . length ( ) / ( 1024 * 1024 * 1024 ) ) ; } /**  * Get File size in MB  * @author  * @param file  * @return  */ public static String getFileSizeMegaBytes ( File file ) {