Today I wrote a small Java program to find files on my harddisk, partly because Windows lacks a proper one and partly because it was for fun. It simply iterates over all childs of a directory and recursively through all their children if they are directories. But then I had a NullPointerException. After some System.out.println()'s and a try-catch blockI found out this happened on some directories like D:\System Volume Information, C:\Users\Public\Documents\My Videos and C:\ProgramData\Templates. Windows itself says, when input in the Explorer address bar “Access denied”. When exploring, they seem to be locked. The source from java.io.File tells me:
public File[] listFiles() {
String[] ss = list();
if (ss == null) return null; //This line seems to cause the NPE
int n = ss.length;
File[] fs = new File[n];
for (int i = 0; i < n; i++) {
fs[i] = new File(ss[i], this);
}
return fs;
}
My question is, why is there no proper say, IOException, SecurityException, or even an IDontCareWhatKindOfExceptionButPleaseNoNullPointerExceptionException?
I know I can just try-catch for NPEs, or check for null, but I’m really curious of why there’s no proper Exception thrown.
Since I dislike try/catch and checking for null because of the aesthetic value of code, I made some nasty, nasty reflection code (with lots of hypocritical try/catch blocks) which emulates some methods from java.io.File, since they’re private, and some packages (like java.io.FileSystem) are not visible. And because I do not care about some Windows files, I simply ignore them using this code, giving me an empty array:
public static File[] listFiles(File mThis) {
String[] ss = list(mThis);
if (ss == null) {
//System.out.println("ss is null");
return new File[] {};
}
int n = ss.length;
File[] fs = new File[n];
for (int i = 0; i < n; i++) {
fs[i] = getNewFile(ss[i], mThis);
}
return fs;
}
EDIT: to avoid misinterpretations: I do use try/catch, I merely don’t like them aesthetically.
EDIT2: I’d rather use a GUI than the command prompt. And I very much dislike the Windows Search GUI. It’s almost painful to use.
Short answer:
FilesAPI.You will never come back to
Fileafter that.