如何在Java中获取文件大小

时间:2020-02-23 14:34:20  来源:igfitidea点击:

在本教程中,我们将看到如何在Java中获取文件大小。
我们可以直接使用java.io.file的长度方法以使其大小以字节为单位。
我们可以相应地将其转换为KB和MB。

package org.igi.theitroad;
 
import java.io.File;
 
public class GetSizeOfFileMain {
 
	public static void main(String[] args) {
	
		//Read the file
		File mp3File=new File("/Users/igi/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");
		
 
	}
 
}

运行上面的程序时,我们将获取以下输出:

Size of file in bytes :3699969.0 bytes
Size of file in KB :3613.2509765625 KB
Size of file in MB :3.5285654067993164 MB