I have a situation where I need to run a "pre-check" to see if a directory is "createable". This is not a problem, just run a file.mkdirs()
and see if it returns true.
The problem is that I would like to clean up after this check. This is a bit tricky, because I want to delete only those folders and subfolder that mkdirs()
actually created.
Can anyone think of a clever way to do this?
I think this method does the job without you having to call mkdirs
:
public static boolean canMkdirs(File dir) {
if(dir == null || dir.exists())
return false;
File parent = null;
try {
parent = dir.getCanonicalFile().getParentFile();
while(!parent.exists())
parent = parent.getParentFile();
} catch(NullPointerException | IOException e) {
return false;
}
return parent.isDirectory() && parent.canWrite();
}