Java Delete File with Files.deleteIfExists() Method Example

In this example, I show you how to delete a file in Java using Files.deleteIfExists() API.

Files.deleteIfExists(Path path) API

This method deletes a file if it exists.

Java Files.deleteIfExists() API Example


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JavaDeleteFile {

    public static void main(String[] args) throws IOException {

        Path myPath = Paths.get("src/sample1.txt");

        boolean fileDeleted = Files.deleteIfExists(myPath);

        if (fileDeleted) {

            System.out.println("File deleted");
        } else {

            System.out.println("File does not exist");
File deleted

The above example deletes a file from location "src/sample1.txt".
The Files.deleteIfExists() deletes a file and returns true if the file was deleted and false if the file could not be deleted because it did not exist.
boolean fileDeleted = Files.deleteIfExists(myPath);