×

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

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 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.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

How to create an array in Java

An array is a linear data structure stores a collection of fixed number ofelements of similar type. The size of an array is specified when it is created. The array...

14 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Java Comparable Interface

We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic...

1 minute read.