Java delete directory
The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful methods that may use to execute actions on folders or folders.
One of the most crucial functions of the File class is deleted (), which is employed to material rapidly and empty folders from the existing File organism's representation.
Should note that the delete() function cannot be employed to deactivate a directory that includes files directly. We remove the folder after emptying the directory to get rid of it.
Furthermore, two methods exist to erase files and directories from either system. The File.delete() function and the Commons-IO.deleteDirectory() method.
Using File.delete() Method
A directory can be deleted using the File class' delete() function. We first execute a consumer function, delete the directory(), which deletes the subfile or subdirectory before utilizing the remove() function.
Let's look at an example to comprehend further how the remove() function works.
Example: DeleteDirectoryEx1.java
//this program is for deletion of the directory in java
//importing the required packages
import java.io.*;
import java.util.*;
import java.io.File;
import java.util.Scanner;
// utilising the delete() function of the File class, develop the class DeleteDirectoryEx1 for removing directories.
public class DeleteDirectoryEx1 {
// main method of the program
public static void main(String args[]) {
String filePath;
// an object is created for the class Scanner for reading the input
Scanner sca= new Scanner(System.in);
System.out.println(" Please enter the path of the directory for deleting.");
filePath = sca.nextLine();
// closing up the scanner class
sca.close();
// an object is created for the file class for reading the path
File files = new File(filePath);
try{
// When to delete a user-provided directory, use the Document's delete() function.
deleteDirectory(files);
// To delete a user-provided directory, just use Document's delete() function.
files.delete();
System.out.println("The entered directory is deleted.");
}catch(Exception e1) {
System.out.println(e1.getMessage());
}
}
// When deleting a subscriber subdirectory, utilize the delete() method of the Documents.
public static void deleteDirectory(File files)
{
// listFiles() is a function to fetch sub-files.
for (File subfiles : files.listFiles()) {
//Execute the deleteDirectory() function repeatedly if, indeed, the subfile is just a directory.
if (subfiles.isDirectory()) {
// To determine if a subfile is a subdirectory or otherwise, use the isDirectory() function.
deleteDirectory(subfiles);
}
//To remove files and blank folders, use the delete() function.
subfiles.delete();
}
}
}
Output
Please enter the path of the directory for deleting.
/Users/mprashanthrao/Documents/Projects
The entered directory is deleted