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

Java File Handling Programs »





Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.