java 如何强制 mkdir 覆盖现有目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26392685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I force mkdir to overwrite existing directory?
提问by labananala
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;
}
回答by Aaron Hall
You want to delete the directory first if it exists, then recreate it.
如果目录存在,您想先删除它,然后重新创建它。
if (Files.exists(path)) {
new File("/dir/path").delete();
}
new File("/dir/path").mkdir();
and if you have FileUtils, thismight be preferable as it avoids actually deleting a directory you want to be there:
如果你有FileUtils,这可能更可取,因为它避免了实际删除你想要在那里的目录:
import org.apache.commons.io.FileUtils
if (Files.exists(path)) {
FileUtils.cleanDirectory( new File("/dir/path"));
} else {
new File("/dir/path").mkdir();
}
回答by euthimis87
You can import this library import org.apache.commons.io.FileUtils;
and then you could write your code like this:
你可以导入这个库import org.apache.commons.io.FileUtils;
,然后你可以像这样编写代码:
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;
}
回答by Justin Kiang
Check if the directory exists, If so, delete that directory
Create directory
检查目录是否存在,如果存在,删除该目录
创建目录