How to Delete file in Java?

It’s a pleasure to meet you again with an interesting yet simple tutorial. Deletion is one of the fundamental operations in file manipulation. As we all know, the java.io package and java.nio package provides all the needed classes and methods for file manipulation. We will use the delete methods in the packages mentioned above to delete a file in java. In this article, We will get a detailed view of how to delete a file in java. Come on, folks! Let us begin.

Methods to delete a file in Java

Following are the methods to delete a file in java.

1. File.delete().

2. File.deleteOnExit().

3. Files.delete().

4. Files.deleteIfExists().

methods to delete a file

Exceptions to be handled:

It is necessary to use a try-catch block for exception handling. We must handle the following few exceptions. They are:

1. NoSuchFileException

2. DirectoryNotEmptyException

3. IOException

4. SecurityException

5. FileNotFoundException

For Example: 

In this article, Consider a file named FirstCode.txt present in the path given below:

E:/FirstCode

To demonstrate file deletion, we will use the file mentioned above.

1. Java File.delete():

The delete() method is a part of the File class in the java.io package. It is a built-in method that deletes both a file and a directory. This method will delete a folder or directory only when it is empty. Instead of moving it to the recycle bin, this method will permanently delete the file or directory from your system.

Method signature:

public boolean delete() 

The return type of this delete() method is a boolean. So, it will return true if the file gets deleted. Otherwise, it returns false.

Syntax:

File fileObject = new File(“path/filename”);
fileObject.delete();

Code to delete a file in java:

Consider the following code to delete a file.

import java.io.File;

public class DeleteFile {
    public static void main(String[] args) {
        try {
            File file = new File("E:\\FirstCode.txt");
                if(file.delete()) {
                    System.out.println("The file named  "+file.getName()+ " is deleted.");
                }
                else {
                    System.out.println("Deleting attempt failed.");
                }
        }
        catch(Exception exception) {
            exception.printStackTrace();
        }
    }

}

Output:

  • If the file deletion is successful, the output will be as below.

The file named FirstCode.txt is deleted.

  • The output will be as shown below for the following condition.
  1. The file does not exist.
  2. The file deletion process fails.

Deleting attempt failed.

Code to delete a directory in java:

To delete a directory, it must be empty. Let us first discuss the code to delete an empty directory.

import java.io.File;

public class DeleteFile {
    public static void main(String[] args) {
        try {
            File file = new File("E:\\FirstCode");
                if(file.delete()) {
                    System.out.println("The directory with name  "+file.getName()+ " is deleted.");
                }
                else {
                    System.out.println("Deleting attempt failed.");
                }
        }
        catch(Exception exception) {
            exception.printStackTrace();
        }
    }

}

Output:

  • If the folder deletion is successful, the output will be as shown.

The directory with name FirstCode is deleted.

  • The output will be as shown below for the following condition.
  1. The folder or directory does not exist.
  2. The folder or directory deletion process fails.
  3. The directory is not empty.

Deleting attempt failed.

To delete a directory with files, First, we must delete the files and make the directory empty. Then we have to delete the directory. Consider the following code to understand better.

import java.io.File;

public class DeleteFile {
    public static void deleteDirectory(File file)
    {
        // Getting all the files and folders in the specified directory and iterating it.
        for (File subfile : file.listFiles()) {
            // if it is a subfolder recursively calling the function.
                if (subfile.isDirectory()) {
                deleteDirectory(subfile);
            }
  
            // Deleting files and empty subfolders
            subfile.delete();
        }
    }
  
    public static void main(String[] args)
    {
    	try {
        // Storing the file path.
        String filepath = "E:\\FirstCode";
        File file = new File(filepath);
        if(file.exists()) {
        // Calling the deleteDirectory function to delete the subdirectory and files
        deleteDirectory(file);
  
        // deleting the main folder
        file.delete();
        if(file.exists()) {
      	  System.out.println("Delete attempt failed.");
      }
      else {
      	  System.out.println("Delete attempt successful.");
      }
        }
        else {
        	System.out.println("The folder does not exist.");
        }
    	}
    	catch(Exception exception) {
    		exception.printStackTrace();
    	}
      
    }

}

Output:

  • If the directory deletion is successful, the output will be as shown.

Delete attempt successful

  • If the directory is not present, the output will be as shown.

The folder does not exist.

2. Java File.deleteOnExit():

This method is also a part of the File class in the java.io package. It deletes the file in reverse order, which means it gets deleted when JVM terminates. We should be cautious while using this method because we cannot cancel the delete request once we make it. Mainly, we use this method to delete the temporary files. Temporary files store temporary data that are not important. So we have to delete the temporary files when JVM terminates.

Method signature:

public void deleteOnExit()

The return type of this method is void. So, it will not return anything.

Syntax:

File fileObject = new File(“path/filename”);
fileObject.deleteOnExit();

a. Consider the following code to delete a temporary file using the deleteOnExit() method.

import java.io.File;

public class DeleteFile {
    
    public static void main(String[] args)
    {
    	try {
        //Creating a temp file named FirstCode.
    		File temp = File.createTempFile("FirstCode", ".temp");
    		System.out.println("The temporary file is created at:  "+temp.getAbsolutePath());
    		temp.deleteOnExit();
    		System.out.println("Temp file exists: "+temp.exists());
    	}
    	catch(Exception exception) {
    		exception.printStackTrace();
    	}
      
    }

}

Output:

After running the program, terminate the JVM. You can confirm the deletion by checking the presence of the file in the corresponding folder.

The output will be:

The temp file is created at: C:\Users\GOWSI\AppData\Local\Temp\FirstCode9451206892234631910.temp

Temp file exists: true

b. Consider the following code to delete a normal file using deleteOnExit() method.

import java.io.File;

public class DeleteFile {
    
    public static void main(String[] args)
    {
    	try {
    		File file = new File("E:\\FirstCode.txt");
    		file.deleteOnExit();
    		System.out.println("File exists: "+file.exists());
    	}
    	catch(Exception exception) {
    		exception.printStackTrace();
    	}
      
    }

}

Output:

  • After running the program, terminate the JVM. Again run the program to confirm the file deletion. You can also confirm the deletion by checking the presence of the file in the corresponding folder.

The output will be:

File exists: true

  • If the folder or file does not exist in the specified path, the output will be:

File exists: false

3. Java Files.delete():

This delete() method is a part of the Files class in java.nio package. This method does not return anything. If it fails to delete the file, it throws an exception. If the given file is not present, it throws NoSuchFileException. This method also deletes both files and empty directories.

Method Signature:

public static void delete(Path path) throws IOException

This method is void, so it returns nothing. We pass the file path as an argument to this method.

Syntax:

String fileName = “Path/Filename”;
Files.delete(Paths.get(fileName));

Code to delete a file:

Consider the following code to delete a file.

import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFile {
    
    public static void main(String[] args)
    {
    	try {
    		String fileName ="E:/FirstCode.txt";
        //Checking whether the specified file exists to handle NoSuchFileException.
    		if(Files.exists(Paths.get(fileName)))
    		{
    		Files.delete(Paths.get(fileName));
    		System.out.println("The file is deleted.");
    		}
    		else
        {
    			System.out.println("The file does not exist.");
        }
     	}
    	catch(Exception exception) {
    		exception.printStackTrace();
    	}
      
    }

}

Alternative code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;

public class DeleteFile {
    
    public static void main(String[] args)
    {
    	try {
    		String fileName ="E:/FirstCode.txt";
    		Files.delete(Paths.get(fileName));
    		System.out.println("The file is deleted.");
    		}
    		
    	catch(NoSuchFileException exception) {
    		System.out.println("The file does not exist.");
    	}
    	catch(IOException exception) {
    		System.out.println("Invalid inputs.");
    	}
      
    }

}

Output:

  • If the file deletion is successful, the output will be as shown.

The file is deleted.

  • If the file is not present, the output will be as shown.

The file does not exist.

Code to delete an empty directory:

To delete a directory, it must be empty. If the directory is not empty, it throws DirectoryNotEmptyException. Let us first discuss the code to delete an empty directory.

import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFile {
    
    public static void main(String[] args)
    {
    	try {
    		String fileName ="E:/FirstCode";
//Checking whether the specified folder exists to handle NoSuchFileException.
    		if(Files.exists(Paths.get(fileName)))
    		{
//Checking whether the specified folder is empty to handle DirectoryNotEmptyException.
    			if(Files.list(Paths.get(fileName)).count()!=0) {
    				System.out.println("The directory is not empty.");
    			}
    			else {
    				Files.delete(Paths.get(fileName));
    	    		System.out.println("The directory is deleted.");
    				
    			}
    		}
    		else
    			System.out.println("The directory does not exists.");
     	}
    	catch(Exception exception) {
    		exception.printStackTrace();
    	}
      
    }

}

Alternative code:

import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;

public class DeleteFile {
    
    public static void main(String[] args)
    {
    	try {
    		String fileName ="E:/FirstCode";
    		Files.delete(Paths.get(fileName));
    		System.out.println("The directory is deleted.");		
    		
     	}
    	catch(DirectoryNotEmptyException exception) {
    		System.out.println("The directory is not empty.");
    	}
    	catch(NoSuchFileException exception) {
    		System.out.println("The directory does not exist.");
    	}
    	catch(IOException exception) {
    		System.out.println("Invalid inputs.");
    	}
      
    }

}

Output:

  • If the directory deletion is successful, the output will be as shown.

The directory is deleted.

  • If the directory is not present, the output will be as shown.

The directory does not exist.

  • If the directory is not empty, the output will be as shown.

The directory is not empty.

4. Java Files.deleteIfExists():

This deleteIfExists() method is a part of the Files class in java.nio package. It does not throw any Exceptions on failure. This method also deletes both files and empty directories.

Method Signature:

public static boolean deleteIfExists(Path path) throws IOException

The return type of this deleteIfExists() method is a boolean. So, it will return true if the file gets deleted. Otherwise, it returns false. We pass the file path as an argument to this method.

Syntax:

String fileName = “Path/Filename”;
Files.deleteIfExists(Paths.get(fileName));

Code to delete a file:

Consider the following code to delete a file.

import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFile {
    
    public static void main(String[] args)
    {
    	try {
    		String fileName ="E:/FirstCode.txt";
    		if(Files.deleteIfExists(Paths.get(fileName)))
    		{
    		System.out.println("The file is deleted.");
    		}
    		else {
    			System.out.println("Deleting attempt failed.");
    		}
     	}
    	catch(Exception exception) {
    		exception.printStackTrace();
    	}
      
    }

}

Output:

  • If the file deletion is successful, the output will be as shown.

The file is deleted.

  • The output will be as shown below for the following condition.
  1. The file does not exist.
  2. The file deletion process fails.

Deleting attempt failed.

Code to delete a directory:

To delete a directory, it must be empty. Let us first discuss the code to delete an empty directory.

import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFile {
    
    public static void main(String[] args)
    {
    	try {
    		String fileName ="E:/FirstCode";
    		if(Files.deleteIfExists(Paths.get(fileName)))
    		{
    		System.out.println("The folder is deleted.");
    		}
    		else {
    			System.out.println("The folder does not exist.");
    		}
     	}
    	catch(DirectoryNotEmptyException exception) {
    		System.out.println("The directory is not empty");
    	}
    	catch(IOException e) {
    		System.out.println("Invalid permissions");
    	}
      
    }

}
  • Output:
    If the directory deletion is successful, the output will be as shown.

The folder is deleted.

  • If the directory is not present, the output will be as shown.

The folder does not exist.

  • If the directory is not empty, the output will be as shown.

The directory is not empty.

Summary

A great thank you for patiently reading this article. In this article, we saw a fundamental file manipulation called the delete operation. I hope this article gives you a better understanding of deleting a file in java. No more waiting! Practice and master programming skills.

Leave a Reply

Your email address will not be published. Required fields are marked *