1

my program counts and prints out the number of files of folder and the total size in bytes of all files but i have error ("Exception in thread "main" 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");
    }

}
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
hackour
  • 95
  • 1
  • 11

1 Answers1

0

you're assuming File[] a = f.listFiles() will always result in a non-null value. this isn't true for empty directories and files. try adding some guard code for this condition, like:

    ...
    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);
    ...
homerman
  • 3,369
  • 1
  • 16
  • 32
  • first the program is fine print the the total size of folder applet but when i creat new folder in folder applet the program make this error i put if(a!=null) but the program doesn't print the total size of folder with the size of subfolder thx for help NOTE:("first the applet folder have only files") – hackour Jun 19 '16 at 21:48
  • the problem was in a(a[i].getName()); it should be size+=a(a[i].getname()); – hackour Jun 20 '16 at 20:09