Java Delete File Sample Code

This sample Java code will attempt to delete a file from the file system. The File delete() method will return a boolean that is true if the file was able to be deleted or false if the file was not able to be deleted. Unsuccessful deletion may be due to file not present or improper file permissions.

It’s also worth noting that the delete() method can also delete a directory or folder. The folder or directory must be empty in order for it to be deleted.

Java Class: File
Method Name: delete()
Parameters: none
Return Type: boolean
Exceptions: SecurityException

Java File Delete Source Code:



public class JavaDeleteFile 

	public static void main(String[] args) 
		String sampleJavaFile = "C:\\Users\\Admin\\Documents\\JavaFileTest1.txt";
			//Create a File object
			File file = new File(sampleJavaFile);
			//Delete the file or directory
				System.out.println(file.getName()+" Has Been Deleted!");
				System.out.println("Problem Deleting File or Directory: "+file.getName());
		catch(Exception ex)


Here is the sample output if the file or directory exists and was successfully deleted from the file system.

Java File Delete Output:

JavaFileTest1.txt Has Been Deleted!

Here is the sample output if the file or directory was NOT able to be deleted from the file system.

Java File Delete Output:

Problem Deleting File or Directory: JavaFileTest1.txt

The Java File class also has a related method called deleteOnExit(). If an application calls this method to delete a file or directory, it will attempt to delete file or directory just before exiting the virtual machine. Use this method with caution because once a deletion has been requested, it is not possible to cancel the request.

In terms of a practical application, I suppose this method would be useful when an application uses temporary files that it would like cleaned up upon exiting.


Add a Comment

Your email address will not be published. Required fields are marked *