0

I am learning the Java I/O, and there is one exercise that finding the maximum and minimum files in the directory

C:\Windows

I wrote the following program, while the compiler complains:

Exception in thread "main" java.lang.NullPointerException
at file.TestFile.compareFile(TestFile.java:25) 
at file.TestFile.compareFile(TestFile.java:27) 
at file.TestFile.compareFile(TestFile.java:27) 
at file.TestFile.main(TestFile.java:18)

This is my code:

package file;

import java.io.File;
import java.io.IOException;

public class TestFile {
    static double MaxSize = 0;
    static double MinSize = Double.MAX_VALUE;
    static File MaxFile = null;
    static File MinFile = null;

    public static void main(String[] args) throws IOException {
        File f = new File("C:\\Windows");
        File[] fs = f.listFiles();
//      System.out.println(fs[10]);
//      if (true)
//          return;
        compareFile(fs);

        System.out.printf("The maxi file is %s, its size is %,d bytes", MaxFile.getAbsolutePath(), MaxSize);
        System.out.printf("The mini file is %s, its size is %,d bytes", MinFile.getAbsolutePath(), MinSize);
    }

    public static void compareFile(File[] files) {
        for (File x : files) {
            if (x.isDirectory())
                compareFile(x.listFiles());
            if (MaxSize < x.length()) {
                MaxSize = x.length();
                MaxFile = x;
            }
            if (MinSize > x.length() && x.length() != 0) {
                MinSize = x.length();
                MinFile = x;
            }
        }
    }
}

What I am confused is when I add the 3 lines of debugging code (comment out here), the fs is not a null pointer. It can get the File element

Oliver
  • 147
  • 9

2 Answers2

1

The Javadoc has an answer, and will in many cases in your carreer.

It explains that the method you invoke can return null, and in which case. The rest is up to you!

Saucistophe
  • 314
  • 2
  • 10
1

Well the error is not inside main but in the method compareFile. As you call it recursively eventually you might find yourself inside a folder with no files in it. In that case you have call the compareFile() with the x.listFiles() as an argument which in that case will be null.

In order to fix the error just check if the files == null and return at the start of the compareFile method.

JKostikiadis
  • 2,847
  • 2
  • 22
  • 34