Java – how do I force MKDIR to overwrite an existing directory?
•
Java
I need my program to create a directory with a specific name and overwrite any existing directory with that name At present, my program seems unable to overwrite the directory Is there any way to force coverage?
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 am trying the following operation, but the program does not detect the existence of the directory, even if it does exist
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;
}
}
Solution: (if someone needs to know in the future...) I finally did 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;
}
Solution
If a directory exists, you must first delete it and then recreate it
Using java. nio. file. Files
if (Files.exists(path)) {
new File("/dir/path").delete();
}
new File("/dir/path").mkdir();
If you have FileUtils, this might be better because it avoids actually deleting the directory you want there:
import org.apache.commons.io.FileUtils
if (Files.exists(path)) {
FileUtils.cleanDirectory( new File("/dir/path"));
} else {
new File("/dir/path").mkdir();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
