错误java IO文件夹的总大小

时间:2016-06-19 00:01:19

标签: java file io

我的程序计算并打印出文件夹的文件数和所有文件的总大小(以字节为单位)但我有错误(“线程中的异常”主“java.lang.NullPointerException”)

import java.io.*;
public class Ex5 {
    public static void a(String s) throws IOException{

        long size=0;
        File f=new File(s);
        File [] a=f.listFiles();
        System.out.println("the number of files in this folder :"+a.length);
        for(int i=0;i<a.length;i++){
        if(a[i].isFile()){
            size=size+a[i].length();

        }else
            a(a[i].getName());

        }
    System.out.println("the folder size is :"+size);
    }
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
      a("C:\\Users\\hackour\\Documents\\javablue\\applet");
    }

}

1 个答案:

答案 0 :(得分:0)

您认为File[] a = f.listFiles()将始终导致非空值。对于空目录和文件,这不是真的。尝试为这种情况添加一些保护代码,例如:

    ...
    File[] a = f.listFiles();
    if(a != null) {
        System.out.println("the number of files in this folder :" + a.length);
        for (int i = 0; i < a.length; i++) {
            if (a[i].isFile()) {
                size = size + a[i].length();

            } else
                a(a[i].getName());

        }
    }
    System.out.println("the folder size is :" + size);
    ...