Delete File In Java

If you need to work with files, Java provides a File class that contains many built-in methods for file handling, such as createNewFile(), mkdir(), and getAbsolutePath(). Each method performs a specific function. For example, createNewFile() creates a new empty file, while mkdir() creates a directory. If you want to delete a file or folder (provided it’s empty), the File class also has a delete() method.

Post On:Delete File In Java
Post Type:Java Tutorials
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:SoftwareTestingo Telegram Group

Delete File In Java

If you want to delete a file in Java, use the delete() method from the Files class. You can also use the delete() method on an object, an instance of the File class.

  • What is a delete() method
  • How to work with the delete() method
  • How to delete a file in Java
  • How to delete a Folder in Java

What is a delete() method?

The delete() method is a built-in method of the File class that can be used to delete/remove a specific file or empty directory. The delete() method will not move the specified file or directory to the recycle bin; instead, it will delete them permanently.

How do you work with the delete() method?

The first thing we need to do is import the File class from the java.io package using the import keyword:

import java.io.File;

After you import the File class, you can create an object of that class. This gives you access to all the functionalities of the File class.

How to Delete File in Java?

There are several ways to delete files in Java: the standard library and third-party libraries. We will cover the following aspects with examples:

  • Deleting a File Using the Files class
  • Delete a file using deleteIfExists()
  • Delete Using File.deleteOnExit() method

Delete File Using the Files class

If you want to delete a file, all you need to do is import the File class, create an object of that class, and specify the file’s name within parentheses. Then, use the object of the class with the delete() method to remove the specified file.

package com.SoftwareTestingO.IO;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class DeleteFile 
{
	public static void main(String[] args) 
	{
		Path path = FileSystems.getDefault().getPath("e:/newFile.txt");
		try 
		{
			Files.delete(path);
			System.out.println("File Deleted Sucessfully");
		} 
		catch (NoSuchFileException x) 
		{
			System.err.format("%s: no such" + " file or directory%n", path);
		} catch (IOException x) {
			System.err.println(x);
		}
	}
}

It’s helpful to know that we can use the delete() method on an object, which is an instance of the File class.

package com.SoftwareTestingO.IO;
import java.io.File;
public class DeleteFile1 
{
	public static void main(String[] args) 
	{
		File myFile = new File("E://newFile.txt");
		if (myFile.delete()) 
		{
			System.out.println("Deleted the file: " + myFile.getName());
		} else 
		{
			System.out.println("Failed to delete the file.");
		}
	}
}

Delete File using deleteIfExists()

This code uses the deleteIfExists() method to delete a file. The advantage of this method is that if the file does not exist, the NoSuchFileException is not thrown (no exception is thrown).

package com.SoftwareTestingO.IO;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
public class DeleteFile2 
{
	public static void main(String[] args) 
	{
		Path path = FileSystems.getDefault().getPath("E://newFile.txt");
		try 
		{
			Files.deleteIfExists(path);
		} 
		catch (IOException x) 
		{
			System.err.println(x);
		}
	}
}

Note: java.nio.file is a new package introduced to deal with files in Java..

Delete File Using File.deleteOnExit() method.

The File.deleteOnExit() method will delete the file or directory defined when the JVM terminates. Remember that it deletes files in reverse order, so make sure your most important files are listed last. This method does not return any value, and once the request is made, it cannot be canceled, so use it cautiously.

Deleting temporary files when the JVM terminates is generally a good idea. Temporary files typically store less important or transient data and can be safely deleted when no longer needed. If you need to delete a .temp file manually, the File.deleteOnExit() method can be used for this purpose.

package com.SoftwareTestingO.IO;
import java.io.File;
public class DeleteFile3 
{
	public static void main(String[] args) 
	{
		try 
		{
			//creates a file instance
			File file = new File("e:\\myNewfile.txt");  
			//Creating a File
			if (file.createNewFile()) 
			{
				System.out.println("File created");
			}
			else
			{
				System.out.println("File already exists!");
			}
			Thread.sleep(5000);

			//deletes the file when JVM terminates  
			file.deleteOnExit(); 

			System.out.println("File Deleted");
			Thread.sleep(1000);
		}
		catch(Exception e) 
		{
			e.printStackTrace();
		}
	}
}

How to delete a Folder in Java?

If you want to delete an empty directory, you can use the delete() method. If a folder contains some files and you want to delete that non-empty folder, you must first delete its files.

package com.SoftwareTestingO.IO;
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class DeleteDirectory 
{
	public static void main(String[] args) 
	{
		Path path = FileSystems.getDefault().getPath("E:\\test");
		try 
		{
			// deleteIfExists() will not throw any 
			//Files.deleteIfExists(path);
			
			Files.delete(path);
			System.out.println("Folder Deleted");
		}
		catch (NoSuchFileException x) 
		{
			System.err.format("%s: no such" + " file or directory%n", path);
		}
		catch (DirectoryNotEmptyException x) 
		{
			System.err.format("%s not empty%n", path);
		}
		catch (IOException x) 
		{
			System.err.println(x);
		}
	}
}

Conclusion:

You’ve reached the end of this article on how to delete files in Java. You should now better understand the various classes and methods used to accomplish these operations on a file, as well as code and outputs for each way. The File class plays an important role in performing these operations, containing many methods.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment