I looked at this and this for information about the NullPointerException, especially with arrays. The links above say that a common pinpoint of NullPointerExceptions is that the object has not been instantiated. I checked my code in case I did not instantiate an array, but I can't seem to find a problem. I've been stuck on this code for quite a while now.
I'm trying to make a program that uses recursion to output all of the files in a program.
import java.io.*;
import javax.swing.*;
public class Driver12
{
public static void main(String[] args) throws Exception
{
String folder = JOptionPane.showInputDialog("Complete path of folder:");
String filename = "";
for(int k = 0; k < folder.length(); k++)
{
char ch = folder.charAt(k);
if(Character.isLetterOrDigit(ch))
filename = filename + ch;
else
filename = filename + '_';
}
System.setOut(new PrintStream(new FileOutputStream(filename + ".txt")));
search(new File(folder));
System.exit(0);
}
public static void search(File f)
{
if(f.isDirectory()) {
File[] array = f.listFiles();
for(int i = 0; i < array.length; i++) {
search(array[i]);
}
}
else {
System.out.println(f.getPath());
}
}
}
When I run the program, and input, say C:\Windows (because I'm on a Windows computer), the program terminates and says:
Exception in thread "main" java.lang.NullPointerException
at Driver12.search(Driver12.java:27)
at Driver12.search(Driver12.java:28)
at Driver12.search(Driver12.java:28)
at Driver12.main(Driver12.java:19)
What is going on here? How can I fix this error?
Any help is greatly appreciated.
Answer
You are using f.listFiles, the moment no files are in the directory, it returns null.
Which crash your programm because it is not null protected.
Note: To debug this, you can use the "Exception breakpoint" functionality from Eclipse. On the debug perspective, simply select the breakpoint tab, then click the "J!" icon and add the exception you wanna catch.
No comments:
Post a Comment