×

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 Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

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

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.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

Java finalize()

Java finalize() In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the...

4 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.