Last Updated:

How do I delete a file or folder in Java?

delete a file or folder in Java

How the delete() method works. Theory

To delete files or folders in Java, use the . It returns if the file was deleted successfully and returns if the file specified for deletion does not exist or cannot be deletedIf you are trying to delete a folder, then this method checks the specified folder for emptiness. If the folder is empty, then it is deleted, if there is something in the folder, then the method simply returns , that is, the folder is not deleted.java.io.File delete()truefalsedelete()false

How the delete() method works. Practice

Let's look at an example of a simple program how to delete a file in Java:

The result of the program:

/Users/prologistic/file.txt file removed
file.txt file has been removed from the project root folder
tmp/file.txt file has been removed from the project root folder
tmp folder has been removed from the project root directory
/Users/prologistic/project was not found in the project root directory or is not empty

Stay tuned for updates in the Java IO section.