How to get the size of a file in Java

In this tutorial, we are going to see how to get the size of a file in Java. The Java File class allows you to get the size in bytes of a file. To get the size of a file, call the length() method of the File class. Here is an example to get the size of a file using the length() method.

How to get the size of a file in Java

public class Main 
    public static void main(String[] args)
		File myFile = new File("C:\\Users\\PC\\Desktop\\test.txt"); 
			double bytes = myFile.length();
			double kiloOctets = (bytes / 1024);
			double megaOctets = (kiloBytes / 1024);
			double gigaOctets = (megaBytes / 1024);

			System.out.println("bytes: " + bytes);
			System.out.println("kilo Bytes : " + kiloBytes);
			System.out.println("mega Bytes : " + megaBytes);
			System.out.println("giga Bytes : " + gigaBytes);
			 System.out.println("File does not exist!");


bytes: 9545.0
kilo Bytes : 5.86478936
mega Bytes : 0.3215879621364002569
giga Bytes : 5.6235425669874100326998754E-6
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *