How to get the size of a file in Java

In Java, you can use the method File.lenght() to find out the size of a file in bytes.

The function  File.lenght()  returns the length in bytes of the file. The return value is undefined if the specified path is a directory.

After getting the file size in bytes, you can convert it as needed to megabytes, gigabytes; etc. But how do you do it? It's easy! A byte is a grouping of 8 bits and represents 256 possible values. So to convert a byte to bits, you just have to multiply by 8. The other units (kilo, mega, giga, tera) are placed in a hierarchy with the unit (n+1) above. is equal to 1024 unit (n) as shown here:
  • one kilobyte (kilobyte) = 1024 bytes
  • one megabyte (megabyte) = 1024 kilobytes
  • one gigabyte (gigabyte) = 1024 megabytes
  • one terabyte (terabyte) = 1024 gigabyte
This Java program creates an instance of  File with the path of a video file as a parameter and displays its size in bits, bytes, kilobytes, megabytes, gigabytes, and terabytes:

import java.io.File; 

public class main
{
public static void main(String[] args)
{
File file =new File("C:\\test.avi");

if(file.exists()){

double bytes = file.length();
double bits = bytes * 8;
double kilobytes = bytes / 1024;
double megabytes = kilobytes / 1024;
double gigabytes = megabytes / 1024;
double terabytes = gigabytes / 1024;

System.out.println("bits: " + bits + "bits");
System.out.println("bytes: " + bytes+ " bytes");
System.out.println("kilobyte: " + kilobytes+ "KB");
System.out.println("megabyte: " + megabytes + "MB");
System.out.println("gigabyte: " + gigabytes + "GB");
System.out.println("terabyte: " + terabytes + "To");
}else{
System.out.println("Non-existent file");
}

}
}
The execution of this code gives:

bits: 4.624187392E9 bits
bytes: 5.78023424E8 bytes
kilobyte: 564476.0KB
megabyte: 551.24609375MB
gigabyte: 0.5383262634277344GB
terabyte: 5.257092416286469E-4TB
References:
Stackoverflow: How to get file size in java?
Wikipedia: Byte