labananala labananala - 3 months ago 32
Java Question

How do I force mkdir to overwrite existing directory?

I need to have my program create a directory with a specific name, and overwrite any existing directory with that name. Currently, my program doesn't seem to be able to overwrite the directory. Is there any way of forcing the overwrite?

private boolean makeDirectory(){
File file = new File(TEMP_DIR_PATH + "/" + clipName);
if (file.mkdir()) {
return true;
}
else {
System.err.println("Failed to create directory!");
return false;
}
}


EDIT:
Now I'm trying the following, but the program is not detecting that the directory exists, even though it does.

private boolean makeDirectory(String path){
File file = new File(path);
if (file.exists()) {
System.out.println("exists");
if (file.delete()) {
System.out.println("deleted");
}
}
if (file.mkdir()) {
return true;
}
else {
System.err.println("Failed to create directory!");
return false;
}
}


RESOLVED:
(If anyone else in the future needs to know...)
I ended up doing it this way:

private boolean makeDirectory(String path){
if (Files.exists(Paths.get(path))) {
try {
FileUtils.deleteDirectory(new File(path));
}
catch (IOException ex) {
System.err.println("Failed to create directory!");
return false;
}
}
if (new File(path).mkdir()) {
return true;
}
return false;
}

Answer

mkdir is an idempotent operation (it just ensures the directory exists by checking if it is there, and if not, creating it), so you need to delete the directory first if it exists, then recreate it.

Using java.nio.file.Files

if (Files.exists(path)) {
    new File("/dir/path").delete();
}    

new File("/dir/path").mkdir();
Comments