Java program to delete empty and non empty directory
Here's a Java program to delete an empty directory:
import java.io.File; public class Main { public static void main(String[] args) { File dir = new File("path/to/empty/directory"); if (dir.delete()) { System.out.println("Directory deleted successfully"); } else { System.out.println("Failed to delete directory"); } } }
This program uses the File
class to represent the directory we want to delete. We then call the delete()
method on this object to delete the directory. If the directory is successfully deleted, the program will print "Directory deleted successfully" to the console. Otherwise, it will print "Failed to delete directory".
Note that this program will only work for empty directories. If the directory contains any files or subdirectories, it cannot be deleted using this method.
Here's a Java program to delete a non-empty directory:
import java.io.File; import org.apache.commons.io.FileUtils; public class Main { public static void main(String[] args) { File dir = new File("path/to/non-empty/directory"); try { FileUtils.deleteDirectory(dir); System.out.println("Directory deleted successfully"); } catch (Exception e) { System.out.println("Failed to delete directory: " + e.getMessage()); } } }
This program uses the Apache Commons IO library to delete a non-empty directory. The FileUtils.deleteDirectory()
method recursively deletes all files and subdirectories in the directory, and then deletes the directory itself. If the directory is successfully deleted, the program will print "Directory deleted successfully" to the console. If an exception occurs, it will print "Failed to delete directory" along with the error message.
Note that you will need to add the Apache Commons IO library to your classpath in order to use this program. You can download the library from the Apache Commons website.