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.
In Java, we can delete a file by using the File. delete() method of File class. The delete() method deletes the file or directory denoted by the abstract pathname. If the pathname is a directory, that directory must be empty to delete.
In Java, the mkdir() function is used to create a new directory. This method takes the abstract pathname as a parameter and is defined in the Java File class. mkdir() returns true if the directory is created successfully; else, it returns false.
Method 1: using delete() to delete files and empty folders Provide the path of a directory. Call user-defined method deleteDirectory() to delete all the files and subfolders.
You make a new directory via mkdir newdirectoryname. You can remove a directory using rmdir directoryname. To remove a directory, you must first remove all the files it contains.
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();
}
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With