C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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.

File.length()

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));
	}
}

Output

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






COMMENTS