i want to search for a file in windows just by giving the name of the file,intially i tried to list out all files using this piece of code
File[] files = File.listRoots();
for(File f : files){
parseAllFiles(f.getPath());
}
...
public static void parseAllFiles(String parentDirectory){
File[] filesInDirectory = new File(parentDirectory).listFiles();
for(File f : filesInDirectory){
if(f.isDirectory()){
parseAllFiles(f.getAbsolutePath());
}
System.out.println("Current File -> " + f);
}
}
but I got an exception saying
Exception in thread "main" java.lang.NullPointerException
at fileoper.parseAllFiles(fileoper.java:24)
at fileoper.parseAllFiles(fileoper.java:26)
at fileoper.parseAllFiles(fileoper.java:26)
at fileoper.main(fileoper.java:19)
Any suggestions on this?
I tried your example. I get a null pointer when trying to open /root
. When I try to open it via terminal, it just says that I don't have the permissions.
So you basically have a problem with permissions.
The javadoc says :
̀Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
In order to catch this, you should check if filesInDirectory
is null.
public static void parseAllFiles(String parentDirectory){
File[] filesInDirectory = new File(parentDirectory).listFiles();
//Added this line.
if(filesInDirectory != null){
for(File f : filesInDirectory){
if(f.isDirectory()){
parseAllFiles(f.getAbsolutePath());
}
System.out.println("Current File -> " + f);
}
}
}