我正在尝试用Java创建一个目录。如果它存在,我想删除该目录及其内容并创建一个新目录。我试图执行以下操作,但不删除该目录。新文件将附加到目录中。
File file = new File("path");
boolean isDirectoryCreated = file.mkdir();
if (isDirectoryCreated) {
System.out.println("successfully made");
} else {
file.delete();
file.mkdir();
System.out.println("deleted and made");
}
我在运行时在正在运行的项目的目录中创建此目录。每次运行后,必须删除旧内容,并且必须在此目录中显示新内容。
答案 0 :(得分:10)
感谢Apache,这非常简单。
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class DeleteFolder {
public static void main(String[] args){
try {
File f = new File("/var/www/html/testFolder1");
FileUtils.cleanDirectory(f); //clean out directory (this is optional -- but good know)
FileUtils.forceDelete(f); //delete directory
FileUtils.forceMkdir(f); //create directory
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:9)
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
答案 2 :(得分:5)
您需要先删除目录中的内容,然后才能删除目录..您可以尝试这样的事情: -
File file = new File("path");
boolean isDirectoryCreated = file.mkdir();
if (isDirectoryCreated) {
System.out.println("successfully made");
} else {
deleteDir(file); // Invoke recursive method
file.mkdir();
}
public void deleteDir(File dir) {
File[] files = dir.listFiles();
for (File myFile: files) {
if (myFile.isDirectory()) {
deleteDir(myFile);
}
myFile.delete();
}
}