Java – Delete File

To delete file in Java, you can use File.delete() function. Call delete() function on the original file.

In this tutorial, we will learn how to delete a file using Java.

Following is the sequence of steps one has to follow to delete a file in Java using File.delete().

  1. Prepare the File object for the file you would like to delete.
  2. Call delete() on the file object. delete() returns true if the file is successfully deleted. Else, it returns false.

Example 1 – Delete File

In this example, we delete a file named data.txt.

Make sure that the file you are deleting is present.

DeleteFile.java

import java.io.File;

/**
 * Java Example Program to Delete File
 */

public class DeleteFile {

	public static void main(String[] args) {
		File originalFile = new File("files/data.txt");
		
		//delete file
		boolean isDeleteDone = originalFile.delete();
		
		//print if the delete operation is successful
		System.out.println("Delete Done: "+isDeleteDone);
	}
}

Run the above Java program.

Output

Delete Done: true

delete() returned true, in other words, the delete operation is successful. Refresh your file system and you will see the file has been deleted.

Example 2 – Delete File – Failure Scenario

Let us now try to delete a file that is not present and see what delete() function returns.

DeleteFile.java

import java.io.File;

/**
 * Java Example Program to Delete File
 */

public class DeleteFile {

	public static void main(String[] args) {
		File originalFile = new File("files/data1.txt");
		
		//delete file
		boolean isDeleteDone = originalFile.delete();
		
		//print if the delete operation is successful
		System.out.println("Delete Done: "+isDeleteDone);
	}
}

Runt the above Java program. We know that, there is no file with the path that delete() function can delete. Therefore, the function returns false.

Output

Delete Done: false

Conclusion

In this Java Tutorial, we learned how to delete File in Java and how to be sure if the delete operation is successful.