Java 获取文件大小

一、API中关于length()的定义

public long length()

Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. 

Where it is required to distinguish an I/O exception from the case that 0L is returned, or where several attributes of the same file are required at the same time, then the Fil es.readAttributes method may be used.

当路径为目录时,得到的是一个无法确定的数。当路径为文件时,得到确切的文件大小。

二、递推遍历所有的子目录

public String detail(String dirName){
		File file = new File(dirName);
		long size = 0;//记录目录的总大小
		List<String> fileList = new ArrayList<>();
		int i=0;
		int count = 0;//记录该初级目录下有多少个文件
		if (file.isDirectory()){
			fileList.add(file.toString());
			for (;i<fileList.size();i++){
				File tempFile = new File(fileList.get(i));
				if (tempFile.isFile()){
					size += tempFile.length();
				}else{
					File[] files = tempFile.listFiles();
					if (i==0){
						count = files.length;
					}
					if (files!=null){//一些文件夹本身就是隐藏的,无法被找到。
						for (int j=0;j<files.length;j++){
							fileList.add(files[j].toString());
						}
					}
				}
				
			}
			return "该文件夹中有"+count+"个文件,总容量为"+size+"字节!";
		}
		return "查询错误!";
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值