Java File deleteOnExit() method with examples

January 04, 2020 No comments Java IO Examples deleteOnExit

1. Introduction

The deleteOnExit() method qualifies the specified file or directory for deletion when the virtual machine terminates. Removal is carried out in reverse order to registering. The delete operation will be attempted only for normal termination of the JVM.

2. Method signature

public void deleteOnExit()

Parameters:

  • method does not take any parameter

Returns

  • method does not return anything

Throws

  • SecurityException - when SecurityManager denies delete access to the file

3. Examples

3.1. Remove file /tmp/frontbackend.txt when JVM terminates

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File file = new File("/tmp/frontbackend.txt");

            file.deleteOnExit();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

No output.

4. Conclusion

In this article, we presented File.deleteOnExit() the method that deletes a file when Java Virtual Machine terminates. Normally this operation happens when we restart the application server or our program stopped. We use this method to eliminate cluttering the operating system and free up unused disk storage resources.

{{ message }}

{{ 'Comments are closed.' | trans }}