问题
I am trying to make a directory in Java. If it exists, I want to delete that directory and its content and make a new one. I am trying to do the following, but the directory is not deleted. New files are appended to the directory.
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");
}
I am creating this directory in runtime in the directory of the running project. After every run, the old contents have to be deleted and new content has to be present in this directory.
回答1:
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:
Thanks to Apache this is super easy.
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();
}
}
}
回答3:
You need to delete first the contents of the directory then only you can delete the directory.. You can try something like this: -
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();
}
}
来源:https://stackoverflow.com/questions/12835285/create-directory-if-exists-delete-directory-and-its-content-and-create-new-one