Java Program to Delete File in Java

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java Program to Delete a file using delete()

import java.io.File;

class Main {
  public static void main(String[] args) {

    // creates a file object
    File file = new File("JavaFile.java");

    // deletes the file
    boolean value = file.delete();
    if(value) {
      System.out.println("JavaFile.java is successfully deleted.");
    }
    else {
      System.out.println("File doesn't exit");
    }
  }
}

In the above example, we have used the delete() method of the File class to delete the file named JavaFile.java.

Here, if the file is present, then the message JavaFile.java is successfully deleted is shown. Otherwise, File doesn't exit is shown.


Example 2: Java Program to Delete a file using deleteIfExists()

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

class Main {
  public static void main(String[] args) {

    try {
      // creates a file object
      Path path = Paths.get("JavaFile.java");

      // deletes the file
      boolean value = Files.deleteIfExists(path);
      if(value) {
        System.out.println("JavaFile.java is successfully deleted.");
      }
      else {
        System.out.println("File doesn't exit");
      }
    } catch (Exception e) {
      e.getStackTrace();
    }

  }
}

Here, we have used the deleteIfExists() method of java.nio.file.Files class. The method deletes the file if it is present in the specified path.

Note: java.nio.file is a new package introduced to deal with files in Java.