How to delete file or folder in java example, code and explantion

How to delete file or folder in java

By Yashwant Chavan, Views 35056, Date 02-Jun-2012

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.

tags java file-delete

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
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]