File

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.

Ilias Tsagklis

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

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button