java通过递归统计文件大小

时间:2019-11-10
本文章向大家介绍java通过递归统计文件大小,主要包括java通过递归统计文件大小使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

思路就是通过文件的遍历,对一个文件夹中的非目录文件进行大小统计,并对其中目录文件进行相同的遍历操作,代码如下:

package word;

import java.io.File;
import java.io.FileNotFoundException;



public class Aa {
    
    static iong numb=0;//总大小
   
    public static void main(String[] args) throws FileNotFoundException {
        // TODO 自动生成的方法存根
        
        

        
        String path = "C:\\File";        //要遍历的路径
        File file = new File(path);        //获取其file对象
        fil(file);
        
        System.out.println(numb);
        
    }

    public static void  fil(File a) throws FileNotFoundException
    {
        String path =a.getPath();
        File file = new File(path);        //获取其file对象
        File[] fs = file.listFiles();    //遍历path下的文件和目录,放在File数组中
        for(File f:fs){                    //遍历File[]数组
            if(!f.isDirectory())        //若非目录(即文件),对其进行遍历
            { 
            numb+=f.length();//获取文件大小}
            else { fil(f);
            }
                
            }
        }
   }
   

原文地址:https://www.cnblogs.com/liuleliu/p/11830617.html