Java Program to Delete a File in Java

In this program, we will learn to delete a file in Java. In Java, you can delete a file using the File class and its delete() method. The File class is used to represent a file or directory in the file system.

Here is an example of how you can delete a file in Java.


public class FileDeleteExample {
  public static void main(String[] args) {
    String fileName = "example.txt";
    File file = new File(fileName);
    if (file.delete()) {
      System.out.println(fileName + " was " +
              "deleted successfully.");
    } else {
      System.out.println("Failed to delete " + fileName);
example.txt was deleted successfully.

In this example, the main method first creates a File object with the file name "example.txt" and then calls the delete() method on it. The delete() method returns true if the file was successfully deleted, or false if the file could not be deleted. If the file is successfully deleted, a message is printed to the console to indicate that the file was deleted successfully. If the file could not be deleted, a message is printed to the console indicating the failure.

It's important to note that the delete() method returns false if the file does not exist or the program doesn't have the permission to delete the file. Also, if the file is a directory and it's not empty, the method throws an exception.

If you want to delete a directory recursively, you can use the FileUtils.deleteDirectory() method from library, which will delete the directory and all its contents.

Also, be careful when deleting files, because once a file is deleted, it can't be recovered.

It's also important to make sure that the file is closed before trying to delete it, if the file is open by another process or in use by the same program it will throw an exception.