Java File example to delete the file or directory defined by the abstract path name using deleteOnExit
By candid | Posted :
Nov 25, 2016
| Updated :
Nov 25, 2016
public void deleteOnExit()
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates. Files (or directories) are deleted in the reverse order that they are registered. Invoking this method to delete a file or directory that is already registered for deletion has no effect. Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification.
Once deletion has been requested, it is not possible to cancel the request. This method should therefore be used with care.
Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.
Program:
package com.candidjava;
import java.io.File;
public class FileDeleteOnExit
{
public static void main(String[] args)
{
File f = null;
try
{
f = File.createTempFile("tem", ".txt");
System.out.println("file path:" + f.getAbsolutePath());
f.deleteOnExit();
f = File.createTempFile("temp", null);
System.out.println("file path:" + f.getAbsolutePath());
f.deleteOnExit();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}