如何在Java中获取文件大小

在Java中,可以使用File.length()方法获取文件大小(以字节为单位)。

获取一个图像文件(c:\\ java_xml_logo.jpg)14KB,并显示文件大小。

package com.mkyong.file;

import java.io.File;

public class FileSizeExample 
{
    public static void main(String[] args)
    {	
		File file =new File("c:\\java_xml_logo.jpg");
		
		if(file.exists()){
			
			double bytes = file.length();
			double kilobytes = (bytes / 1024);
			double megabytes = (kilobytes / 1024);
			double gigabytes = (megabytes / 1024);
			double terabytes = (gigabytes / 1024);
			double petabytes = (terabytes / 1024);
			double exabytes = (petabytes / 1024);
			double zettabytes = (exabytes / 1024);
			double yottabytes = (zettabytes / 1024);
			
			System.out.println("bytes : " + bytes);
			System.out.println("kilobytes : " + kilobytes);
			System.out.println("megabytes : " + megabytes);
			System.out.println("gigabytes : " + gigabytes);
			System.out.println("terabytes : " + terabytes);
			System.out.println("petabytes : " + petabytes);
			System.out.println("exabytes : " + exabytes);
			System.out.println("zettabytes : " + zettabytes);
			System.out.println("yottabytes : " + yottabytes);
		}else{
			 System.out.println("File does not exists!");
		}
    		
    }
}

结果

bytes : 13900.0
kilobytes : 13.57421875
megabytes : 0.013256072998046875
gigabytes : 1.2945383787155151E-5
terabytes : 1.2641976354643703E-8
petabytes : 1.234568003383174E-11
exabytes : 1.205632815803881E-14
zettabytes : 1.1773757966834775E-17
yottabytes : 1.1497810514487085E-20

翻译自: https://mkyong.com/java/how-to-get-file-size-in-java/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值