我的程序计算并打印出文件夹的文件数和所有文件的总大小(以字节为单位)但我有错误(“线程中的异常”主“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");
}
}
答案 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);
...