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