Signup/Sign In

How to Delete a file or directory in Java

In this post, we are going to delete a file or directory by using the Java code. Java provides a File class that contains methods like delete() and deleteOnExit() to delete the specified resource file or a directory.

It is helpful when we want to delete a file using code after creating a new version file that replaces an old version.

The delete() method deletes the file or directory represented by location. If the specified location-path denotes a directory then the directory must be empty.

If file or directory can't be deleted then throw an IOException.

This method returns a boolean value either true or false.


Time for an Example

Let's create an example to delete a file by using the delete() method. This method returns true if the file is deleted successfully.

import java.io.File;
public class Main {

	public static void main(String[] args){
		try {
			File file = new File("abc.txt");
			boolean delete = file.delete();
			if(delete) {
				System.out.println("File is deleted");
			}else {
				System.out.println("File is not deleted");
			}
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}


File is deleted

Example: Delete Directory

We can use delete() method to delete a directory as well. Make sure the specified directory-path denotes an empty directory, if the deletion fails it returns false to the caller function.

import java.io.File;
public class Main {

	public static void main(String[] args){
		try {
			File file = new File("path/to/directory/Trash");
			boolean delete = file.delete();
			if(delete) {
				System.out.println("Directory is deleted");
			}else {
				System.out.println("Directory is not deleted");
			}
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}


Directory is deleted

Example: deleteOnExit() Method

There is another method deleteOnExit() that is used to delete a file or directory when the virtual machine terminates. It means it deletes when the instance of the program terminates.

This method should be used carefully because once deletion has been requested, it is not possible to cancel the request. It does not return any value means returns void to the called function.

import java.io.File;
public class Main {

	public static void main(String[] args){
		try {
			File file = new File("abc.txt");
			// Delete file while exit
			file.deleteOnExit();
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.