Home » Java programs » Java file handling programs

Java program to get the size of give file in bytes, kilobytes and megabytes

In this Java program, we are going to learn how to get the size of a given file in bytes, kilobytes and megabytes?
Submitted by IncludeHelp, on October 27, 2017

Given a file and we have to get the file size using Java program.


This is a method of "File" class, which returns the file’s length (file size) in bytes.

In this program, we are using a file named "includehelp.txt" which is stored in "E:\" in my system, program will get its size in bytes and then we will convert file size in kilobytes and megabytes.

Program to get size of given file in Java

import java.io.*;

public class ReturnFileSize 
	public static void main(String[] args) 
		//create file object.
		// enter the file name.
		File file = new File("E:/includehelp.txt");

		// calculate the size of the file.
		long fileSize = file.length();

		// return the file size in bytes,KB and MB.
		System.out.println("File size in bytes is : " + fileSize);
		System.out.println("File size in KB is : " + (double)fileSize/1024);
		System.out.println("File size in MB is : " + (double)fileSize/(1024*1024));


File size in bytes is : 41
File size in KB is : 0.0400390625
File size in MB is : 3.910064697265625E-5

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.