Java Delete Temporary File

If a Java application needs to create a temporary file for some business logic or unit testing, then we need to make sure that these temporary files are deleted when they are not needed. Let’s learn how to delete a temporary file in Java.

1. File.deleteOnExit()

To delete a file when application exita or completes, you can use deleteOnExit() method. Invoking this method to delete a file or directory that is already registered for deletion has no effect.

Please note that the file deletion will be attempted only for normal termination of the virtual machine. If the program terminates abnormal, the file may not be deleted.

Once deletion has been requested, it is not possible to cancel the request.

Example 1: Deleting a temporary file at the end of the program

import java.io.File;
import java.io.IOException;

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      File temp;
      try
      {
         temp = File.createTempFile("myTempFile", ".txt");
         
         temp.deleteOnExit(); //Delete when JVM exits
         

         //Perform other operations
      } 
      catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

2. File.delete()

To delete a temporary file immediately without waiting for the application termination, we can directly use the delete() method.

If it is invoked for a directory then the directory must be empty in order to be deleted.

Example 2: Java program to delete a file or directory

import java.io.File;
import java.io.IOException;

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      File temp;
      try
      {
         temp = File.createTempFile("myTempFile", ".txt");
         
         //Perform other operations
         
         temp.delete(); //Delete the file immediately
      } 
      catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

3 thoughts on “Java Delete Temporary File”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.