Q:

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

belongs to collection: Java File Handling Programs

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to create directory/folder in particu... >>
<< Java program to check whether a file is hidden or ...