Write a Java Program to Delete Empty and Non-empty Directory

Java Program to Delete Empty and Non-empty Directory

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Delete Empty and Non-empty Directory
Java Program to Delete Empty and Non-empty Directory

Write a Java Program to Delete Empty and Non-empty Directory

PROGRAM: Java Program to Delete Empty and Non-empty Directory

/*Java Program to Delete Empty and Non-empty Directory*/

 1: Java Program to delete an empty directory

import java.io.File;

class Main {
public static void main(String[] args) {

try {
// create a new file object
File directory = new File(“Directory”);

// delete the directory
boolean result = directory.delete();

if(result) {
System.out.println(“Directory Deleted”);
}
else {
System.out.println(“Directory not Found”);
}

} catch (Exception e) {
e.getStackTrace();
}
}
}

2: Delete a non-empty directory

import java.io.File;

class Main {
public static void main(String[] args) {

try {
// create a new file object
File directory = new File(“Directory”);

// list all the files in an array
File[] files = directory.listFiles();

// delete each file from the directory
for(File file : files) {
System.out.println(file + ” deleted.”);
file.delete();
}

// delete the directory
if(directory.delete()) {
System.out.println(“Directory Deleted”);
}
else {
System.out.println(“Directory not Found”);
}

} catch (Exception e) {
e.getStackTrace();
}
}
}

3: Delete non-empty directory recursively

import java.io.File;

class Main {

public static void deleteDirectory(File directory) {

// if the file is directory or not
if(directory.isDirectory()) {
File[] files = directory.listFiles();

// if the directory contains any file
if(files != null) {
for(File file : files) {

// recursive call if the subdirectory is non-empty
deleteDirectory(file);
}
}
}

if(directory.delete()) {
System.out.println(directory + ” is deleted”);
}
else {
System.out.println(“Directory not deleted”);
}
}
public static void main(String[] args) {

try {
// create a new file object
File directory = new File(“Directory”);

Main.deleteDirectory(directory);

} catch (Exception e) {
e.getStackTrace();
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *