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.
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
Program to get size of given file in Java
Output