I want to list all files and directories from a start point using recursion.
Here is my code.
import java.io.File;
import java.io.IOException;
public class RecursiveWalk {
void recursive (File[] allfiles) throws IOException{
for (File file : allfiles) {
if (file.isDirectory()) {
System.out.print("directory:");
System.out.println(file.getCanonicalPath());
recursive (file.listFiles());
} else {
System.out.print(" file:");
System.out.println(file.getCanonicalPath());
}
}
}
public static void main(String[] args) throws IOException {
File f = new File("."); // current directory
File[] allfiles = f.listFiles();
RecursiveWalk test = new RecursiveWalk();
test.recursive(allfiles);
}
}
I have tested it with several directories. Some times fails , but i can't understand why.
The message i get is Exception in thread "main" java.lang.NullPointerException refering to for (File file : allfiles)
.