Home » Core Java » io » File » Delete file/directory

About Ilias Tsagklis

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

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;

import java.io.File;

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

 

Leave a Reply

avatar
  Subscribe  
Notify of