I need one help.
In our application we are deleting some directory and files from disk space through a job
Sometime this job takes much time due to large number of directories and meanwhile that job gets
triggerred for second time and its trying to delete some files which are already deleted by the
first job. As a result we are getting Null Pointer Exception in for (File file : files)
line
because parent.listFiles()
is returning null
To fix this is issue, I can add a null check. But I was thinking if I can use Stream API because I think from performance perspective its little bit ahead of other approach( Please correct me if I am wrong).
So my question is :
Is there any null check in the foreach() method(mentioned below) ?In other words is it safe to use ? I checked that method but I didnt understand much
Please suggest if there is any better approach than this.
Code which is having issue :
public void deleteFile(File parent) {
if (parent.isDirectory()) {
File[] files = parent.listFiles();
for (File file : files) {
deleteFile(file);
}
}
parent.delete();
}
Solution :
Files.walk(rootPath)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.peek(System.out::println)
.forEach(java.io.File::delete);