delete dir java code example
Example 1: How to delete a directory in java
import java.io.File;
public class DeleteDirectoryRecursively
{
public static void main(String[] args)
{
String strFolder = "B:\New folder";
deleteRecursive(new File(strFolder));
}
public static void deleteRecursive(File fl)
{
if(!fl.exists())
return;
if(fl.isDirectory())
{
for(File file : fl.listFiles())
{
deleteRecursive(file);
}
}
fl.delete();
System.out.println("Deleted file/directory: " + fl.getAbsolutePath());
}
}
Example 2: java delete directory
boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}