×

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

Related Topics

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us...

6 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.