Java Program to Delete File in Java

Java Program to Delete File in Java

In this example, we will learn to delete file in using the File and Files class in Java.

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

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.

To learn more on file, visit Java File.


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

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.