How to Delete File in Java?

Free Java courses with 37 real-time projects - Learn Java

We have seen how to create a file, how to open a file, but there might be instances where we might require deleting a file as well. Java also has provisions for that. Unlike create and Open, Java only has two methods to delete a file. In this article, we will discuss how to delete a file in Java.

Deleting a File in Java:

There are two ways to delete a file in Java:

  • Using the File.delete() method.
  • Using the File.deleteOnExit() method.

Let us discuss them at length.

 

initial state

Initially, we can see there are these two text files. We will delete them both using two different methods.

1. Using the Java File.delete() method:

The File class in Java contains the File.delete() method which can delete a file from the desired location. The delete() method can delete both files and directories, as long as the directory is empty. The files and directories are denoted by an abstract pathname in the method.

The method signature is:

public boolean delete()  

If the file/directory is deleted the method returns true else false.

Code to understand the File.delete() method:

package com.DataFlair.FileDelete;
import java.io.File;
public class deleteMethod
{
    public static void main(String[] args)  
        {     
        try  
        {         
            File f_delete= new File("G:\\Internship\\File Delete\\DeleteMethod.txt");      
            if(f_delete.delete())                
            System.out.println("Deletion Complete: "+f_delete.getName()); 
            else  
            System.out.println("Failed!!!!!");  
        }  
        catch(Exception e)  
        {  
            e.printStackTrace();  
        }  
        }
}

The output of the above code:

Deletion Complete: DeleteMethod.txt
deleteonexit method

We can see that the desired file has been removed from the path.

2. Using Java File.deleteOnExit() method:

The File.deleteOnExit() method also works in the same way as the delete() method, the only difference is that this method deletes in reverse order. This method deletes the file when the JVM terminates. It does not return any value, once the deletion request is made, it cannot be reverted back, so this method should be used carefully.

The method signature is:

public void deleteOnExit()  

This method is generally used to delete temporary files of less importance, which should be deleted when terminating the JVM. If we want to delete a .temp file manually, we can always use the delete() method.

Code to understand the working of the deleteOnExit() method:

package com.DataFlair.FileDelete;
import java.io.File;  
import java.io.IOException;  
public class DeleteOnExitMethod
{
    public static void main(String[] args)  
        {     
            File f_delete= new File("G:\\Internship\\File Delete\\DeleteOnExitMethod.txt");         
            f_delete.deleteOnExit();                      
            System.out.println("File exists : " + f_delete.exists());  
        }   
}  

The output of the above code:

File exists : true

Since we did not exit the JVM, the file still exists. Now, if terminate the JVM and then run the code once again, the output will be:

File exists : false

deletemethod state

So, we can see that the file is no longer there in the location, after terminating the JVM.

We already discussed that the deleteOnExit() method is used for temp files in most cases. Let us see an example, how it works.

Code to understand the working of deleteOnExit() method on temp files:

package com.DataFlair.FileDelete;
import java.io.File;  
import java.io.IOException; 
public class DeleteOnExitTemp
{
    public static void main(String[] args)  
    {     
        File temp;  
        try  
        {  
            temp = File.createTempFile("temporay_file", ".temp");     
            System.out.println("Temp file created at location: " + temp.getAbsolutePath());      
            temp.deleteOnExit();                      
            System.out.println("Temp file status: " + temp.exists());  
        }   
        catch (IOException e)  
        {  
            e.printStackTrace();  
        }  
    }   
}  

The output of the above code:

Temp file created at location: C:\Users\ARKAPC~1\AppData\Local\Temp\temporay_file7422334102278577407.temp
Temp file status: true

So, the temporary file created using this program will be deleted on exiting the JVM.

Conclusion:

In this article, we saw how to delete a file in Java using the two methods present in it. Deletion is essential for storage management. If the programmer keeps on creating and using files and does not delete any files, one day the storage will run out, so it is essential to manage the storage efficiently.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

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