Java File deleteOnExit() method with examples

December 02, 2019 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()


  • method does not take any parameter


  • method does not return anything


  • SecurityException - when SecurityManager denies delete access to the file

3. Examples

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



public class FrontBackend {

    public static void main(String args[]) {

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


        } catch (Exception e) {

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 }}