Java Delete File Example

In this source code example, we show you how to delete a file in Java.

We use Files.deleteIfExists() method to delete a file if it exists.

Java Delete File 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/resources/sample.txt");
        boolean fileDeleted = Files.deleteIfExists(myPath);
        if (fileDeleted) {
            System.out.println("File deleted");
        } else {
            System.out.println("File does not exist");


File deleted