File deleteOnExit() in Java

deleteOnExit(): This method is available in the java.io.File class of Java.

Syntax:

void java.io.File.deleteOnExit()

This method 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.

Parameters: NA

Note:

1. Invoking this method to delete a file or directory that is already registered for deletion has no effect.

2. This method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. FileLockfacility should be used instead.

Returns: NA

Throws:

SecurityException - If a security manager exists and its java.lang.SecurityManager.checkDelete method denies deleting access to the file.

Approach

Java

import java.io.File;

public class FiledeleteOnExit {
    public static void main(String[] args) {

        String pathname = "D:\\hello.txt";
        File file = new File(pathname);

        file.deleteOnExit();
        System.out.println(file);
    }
}

Output:

D:\hello.txt


No comments:

Post a Comment