Search code examples
javarecursionnullpointerexception

Why the program throws a NullPointerException after printing out the first java file?


I have implemented the following two methods which are part of a program for printing the sub-directories and the .java files of directory. After printing the first directories and the first java file it throws a NullPointerException. I can't figure out the reason why it doesn't proceed with printing of the rest of the .java files. The two methods are:

public static void printAllJavaFiles(File directory) {
    if ((directory.isDirectory()) || (directory.isFile() && (directory.getName().endsWith(".java"))){
        print(directory);
        depth++;
        File[] subs = directory.listFiles();
        assert subs != null;
        for (File f : subs)
            printAllJavaFiles(f);
        depth--;
    }
 } 
 private static void print(File directory) {
    StringBuilder strb = new StringBuilder();
    for (int i = 0; i < depth; i++)
        strb.append(" ");
    System.out.println((++count)+strb.toString()+directory.getName()+" "+directory.getUsableSpace());
 } 

 1 src 433863356416
 2  .idea 433863356416
 3  am223xi_assign1 433863356416
 4   Area.java 433863356416
 Exception in thread "main" java.lang.NullPointerException
    at am223xi_assign3.PrintJavaMain.printAllJavaFiles(PrintJavaMain.java:22)
    at am223xi_assign3.PrintJavaMain.printAllJavaFiles(PrintJavaMain.java:23)
    at am223xi_assign3.PrintJavaMain.printAllJavaFiles(PrintJavaMain.java:23)
    at am223xi_assign3.PrintJavaMain.main(PrintJavaMain.java:10)

Solution

  • It is throwing null pointer exception because you are using assert subs != null but running the program without -ea VM flag so below the line is throwing null pointer exception

    for (File f: subs) as subs are null for file objects
    

    If you run the program using the "-ea" VM flag, you will end up getting the AssertionError as below.

     1src 276591165440
     2 XXX.java 276591165440
     Exception in thread "main" java.lang.AssertionError
    

    Because the program will terminate after asserting subs != null; as it will fail for file objects.

    Use if instead of assert - it will print all the files in the folder

    public static void printAllJavaFiles(File directory) {
        if ((directory.isDirectory()) || (directory.isFile() && 
       (directory.getName().endsWith(".java")))) {
            print(directory);
            depth++;
            File[] subs = directory.listFiles();
            if(subs != null) {
                for (File f : subs) {
                    printAllJavaFiles(f);
                }
            }
            depth--;
        }
    }