How do I force mkdir to overwrite an existing directory?
I need my program to 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 a way to force 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: I am now trying the following, but the program does not detect that the directory exists, although 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 should know ...) I ended up like this:
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;
}
source to share
You want to first delete the directory if it exists and then recreate it.
if (Files.exists(path)) {
new File("/dir/path").delete();
}
new File("/dir/path").mkdir();
and if you have FileUtils, this option may be preferable as it avoids actually deleting the directory you want to find:
import org.apache.commons.io.FileUtils
if (Files.exists(path)) {
FileUtils.cleanDirectory( new File("/dir/path"));
} else {
new File("/dir/path").mkdir();
}
source to share
You can import this library import org.apache.commons.io.FileUtils;
and then you can write your code like this:
private boolean makeDirectory(){
File file = new File(TEMP_DIR_PATH + "/" + clipName);
boolean returnValue = false;
try {
FileUtils.forceMkdir(file);
returnValue = true;
} catch (IOException e) {
throw new RuntimeException(e);
}
return returnValue;
}
source to share