How to get size of file in java

In this post, we will see how to get size of file in java. We can directly use 's length method to get its size in bytes. We can convert it to KB and MB accordingly.
package org.arpit.java2blog;


public class GetSizeOfFileMain {

	public static void main(String[] args) {
		// Read the file
		File mp3File=new File("/Users/Arpit/Desktop/MySong.mp3");
		// Use length method to get size of file in bytes
		double fileSizeinBytes=mp3File.length();
		System.out.println( "Size of file in bytes :" +fileSizeinBytes + " bytes");
		System.out.println( "Size of file in KB :" +(double)fileSizeinBytes/1024 + " KB");
		System.out.println( "Size of file in MB :" +(double)fileSizeinBytes/(1024*1024) + " MB");



When you run above program, you will get following output:
Size of file in bytes :3699969.0 bytes
Size of file in KB :3613.2509765625 KB
Size of file in MB :3.5285654067993164 MB

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012