How to delete file or folder in java

Below example illustrates how to delete the file or directory. The File class is an abstract representation of file and directory pathnames. Which is part of Java I/O (input/output) java.io package.

File.delete() method

Java file delete() is used to delete the specified file or folder.Returns true if and only if the file or directory is deleted successfully. otherwise returns false

directory structure

c:\demo\one.txt
c:\demo\two.txt
c:\demo\three.txt
c:\demo\four.txt

c:\demo\img\img-1.jpg
c:\demo\img\img-2.jpg

File Delete Example

package com.technicalkeeda.app;

import java.io.File;

public class FileDeleteExample {

    public static void main(String[] args) {
        new FileDeleteExample().delete(new File("c:/demo/one.txt")); // Delete file single file
        System.out.println();
        new FileDeleteExample().delete(new File("c:/demo")); // Delete folder
    }

    private void delete(File file) {
        boolean success = false;
        if (file.isDirectory()) {
            for (File deleteMe: file.listFiles()) {
                // recursive delete
                delete(deleteMe);
            }
        }
        success = file.delete();
        if (success) {
            System.out.println(file.getAbsoluteFile() + " Deleted");
        } else {
            System.out.println(file.getAbsoluteFile() + " Deletion failed!!!");
        }
    }
}

If file or directory not available on the specified path then it return false. It won't give you Exception like FileNotFoundException. Program execute smoothly.

Output

c:\demo\one.txt Deleted

c:\demo\four.txt Deleted
c:\demo\img\img-1.jpg Deleted
c:\demo\img\img-2.jpg Deleted
c:\demo\img Deleted
c:\demo\three.txt Deleted
c:\demo\two.txt Deleted
c:\demo Deleted