Java Program to delete a file or directory when the program ends


A file or directory with the required abstract pathname can be deleted when the program ends i.e. after the virtual machine terminates using the method java.io.File.deleteOnExit(). This method requires no parameters and it does not return a value.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         System.out.println("File: " + file);
         file.deleteOnExit();
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The output of the above program is as follows −

Output

File: demo1.txt

Now let us understand the above program.

The file is deleted when the program ends i.e. after the virtual machine terminates using the method java.io.File.deleteOnExit(). A code snippet that demonstrates this is given as follows −

try {
   File file = new File("demo1.txt");
   file.createNewFile();
   System.out.println("File: " + file);
   file.deleteOnExit();
} catch(Exception e) {
   e.printStackTrace();
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements