Java File example to delete the file or directory defined by the abstract path name using deleteOnExit


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();
        	}
        } 
}

Output:
file path:C:\Users\Sathiya\AppData\Local\Temp\tem3435866396425988007.txt
file path:C:\Users\Sathiya\AppData\Local\Temp\temp5574139238177604374.tmp

Description:
The newly created file in JVM is being deleted on exit of the file. 

Throws:
SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file


Related Post

Comments


©candidjava.com