Java File delete() method with examples

January 04, 2020 No comments Java IO delete Examples

1. Introduction

The delete() method is a part of a Java I/O API. This method deletes the file or directory but assuming the directory is empty. Every time operation cannot be executed the IOException has been thrown and this applies to every method from java.io.File class.

2. Method signature

public boolean delete()

Parameters:

  • method does not take any parameter

Returns

  • true if and only if the file or directory is successfully deleted

Throws

  • SecurityException when access to the file or directory is denied

3. Examples

3.1. Delete an existing file

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f = new File("/tmp/frontbackend.txt");

            if (f.delete()) {
                System.out.println("File deleted");
            } else {
                System.out.println("File was not deleted");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

File deleted

3.2. Delete an empty directory

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f = new File("/tmp/frontbackend");

            if (f.isDirectory()) {
                System.out.println("Remove directory");
            }

            if (f.delete()) {
                System.out.println("Directory deleted");
            } else {
                System.out.println("Directory was not deleted");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

Remove directory
Directory deleted

Trying to delete the directory that does not exist will give the following result:

The directory was not deleted

Trying to delete a directory that is not empty will give the following output:

Remove directory
The directory was not deleted

4. Conclusion

In this article we presented the File.delete() the method from Java I/O API. We used several examples to show how to use it and what results we should expect in different scenarios.

{{ message }}

{{ 'Comments are closed.' | trans }}