How to Delete Files and Directories in Java

To delete a file in Java, we can use the delete() method from Files class. We can also use the delete() method on an object which is an instance of the File class.

Example:

Deleting a File Using the Files class

The code example below shows how to delete a file with the Files class:

import java.io.IOException;
import java.nio.file.*;

public class DeleteFile {

    public static void main(String[] args) {
        Path path = FileSystems.getDefault().getPath("./src/test/resources/newFile.txt");
        try {
            Files.delete(path);
        } catch (NoSuchFileException x) {
            System.err.format("%s: no such" + " file or directory%n", path);
        } catch (IOException x) {
            System.err.println(x);
        }
    }
}

The above code deletes a file named newFile.txt in ./src/test/resources/ directory.

The multiple catch() blocks will catch any errors thrown when deleting the file.

Deleting a File Using the File Class

Instead of using the delete() method on the Files class, we can also use the delete() method on an object which is an instance of the File class.

Example:

import java.io.File;

public class DeleteFile {

    public static void main(String[] args) {
        File myFile = new File("./src/test/resources/newFile.txt");
        if (myFile.delete()) {
            System.out.println("Deleted the file: " + myFile.getName());
        } else {
            System.out.println("Failed to delete the file.");
        }
    }
}

Delete a File if Exists

The following code uses the deleteIfExists() method before deleting a file.

import java.io.IOException;
import java.nio.file.*;

public class DeleteFile {
    public static void main(String[] args) {
        Path path = FileSystems.getDefault().getPath("./src/test/resources/newFile.txt");
        try {
            Files.deleteIfExists(path);
        } catch (IOException x) {
            System.err.println(x);
        }
    }
}

In the above code example, if the file does not exist, the NoSuchFileException is not thrown.

Delete a Directory

We can use the above code to delete a folder as well.

If the folder is not empty a DirectoryNotEmptyException is thrown, so we have to explicitly catch the exception.

import java.io.IOException;
import java.nio.file.*;

public class DeleteFile {

    public static void main(String[] args) {
        Path path = FileSystems.getDefault().getPath("./src/test/resources");
        try {
            Files.deleteIfExists(path);
        } catch (NoSuchFileException x) {
            System.err.format("%s: no such" + " file or directory%n", path);
        } catch (DirectoryNotEmptyException x) {
            System.err.format("%s not empty%n", path);
        } catch (IOException x) {
            System.err.println(x);
        }
    }
}