Delete file/directory

In this example we shall show you how to delete a file or directory. We are using the File class that is an abstract representation of file and directory pathnames. To delete a file or directory one should perform the following steps:

  • Create a new File instance by converting the given pathname string into an abstract pathname.
  • Use delete() API method of File. This method deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted.

Let’s take a look at the code snippet below:

package com.javacodegeeks.snippets.core;


public class DeleteFileDirectory {

	public static void main(String[] args) {

		// delete file
		File file = new File("C://deleteme.txt");
		boolean fileDeleted = file.delete();
		System.out.println("File deleted: " + fileDeleted);

		// delete directory
		File dir = new File("C://deletemedir/");
		boolean dirDeleted = dir.delete();
		System.out.println("File deleted: " + dirDeleted);

This was an example of how to delete a file or directory in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button