Java - File Input Output Delete Files

Introduction

Files class delete(Path p) and deleteIfExists(Path p) can delete a file, a directory, and a symbolic link.

The delete() method throws an exception if the deletion fails.

The deleteIfExists() method does not throw a NoSuchFileException if the file being deleted does not exist.

It returns true if it deletes the file. Otherwise, it returns false.

It throws a DirectoryNotEmptyException if the directory being deleted is not empty.

The following code shows how to delete a file and handle exceptions:

Demo

import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) throws IOException {
    // Create a Path object on Windows
    Path p = Paths.get("C:\\myData\\Main.java");

    try {//from  w w  w . j  av  a 2s  .c o m
      // Delete the file
      Files.delete(p);
      System.out.println(p + " deleted successfully.");
    } catch (NoSuchFileException e) {
      System.out.println(p + " does not exist.");
    } catch (DirectoryNotEmptyException e) {
      System.out.println("Directory " + p + " is not empty.");
    } catch (IOException e) {
      e.printStackTrace();
    }

  }
}

Result