Write a Java Program to Delete File in Java

In Java, deleting a file can be achieved using the java.io.File class.

The File class provides several methods to interact with files, including creating, renaming, and deleting files.

In this tutorial, we’ll focus on how to delete a file using Java.


To delete a file, we first need to create a File object that represents the file we want to delete.

We can create a File object using the constructor that takes a file path as a parameter.

For example, to create a File object that represents a file named “myfile.txt” in the current directory, we can use the following code:

File fileToDelete = new File("myfile.txt");

Once we have a File object that represents the file we want to delete, we can use the delete() method to delete the file.

The delete() method returns a boolean value that indicates whether the file was successfully deleted or not.

For example, to delete the file “myfile.txt”, we can use the following code:

if (fileToDelete.delete()) {
    System.out.println("File deleted successfully.");
} else {
    System.out.println("Failed to delete file.");
}

In the above code, we first check if the file was successfully deleted by checking the return value of the delete() method.

If the delete() method returns true, we print a message indicating that the file was deleted successfully.

Otherwise, we print a message indicating that the deletion failed.

It’s worth noting that the delete() method can throw a SecurityException if the Java virtual machine has denied delete access to the file.

This can happen if the file is read-only, if the file is locked by another process, or if the file is located in a directory for which the Java virtual machine does not have delete permission.

Therefore, it’s a good practice to enclose the call to delete() method in a try-catch block and handle any exceptions that may be thrown.


In conclusion, deleting a file in Java is a straightforward task that can be accomplished using the java.io.File class.

We simply need to create a File object that represents the file we want to delete, and then call the delete() method on that object.

However, we should be aware of the potential exceptions that may be thrown and handle them accordingly.

Editorial Team
Editorial Team

Programming Cube website is a resource for you to find the best tutorials and articles on programming and coding.