Home » Java programming language

Java File Class void deleteOnExit() method with Example

Java File Class void deleteOnExit() method: Here, we are going to learn about the void deleteOnExit() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 16, 2019

File Class void deleteOnExit()

  • This method is available in package java.io.File.deleteOnExit().
  • This method is used to delete the file or directory when the virtual machine terminates.
  • The return type of this method is void so it does not return anything.
  • In this method delete file or directories in the reverse order, that means last created file or directories will be deleted first when virtual machine terminates.
  • This method may raise an exception (i.e. Security Exception) delete access is not given to the file.

Syntax:

    void deleteOnExit(){
    }

Parameter(s):

We don't pass any object as a parameter in the method of the File.

Return value:

The return type of this method is void, it does not return anything.

Java program to demonstrate example of deleteOnExit() method

// import the File class because we will use File class methods import java.io.File; // import the Exception class because it may raise an // exception when working with files import java.lang.Exception; class DeleteFileOnExit { public static void main(String[] args) { try { // Specify the path of file and we use double slashes to // escape '\' character sequence for windows otherwise // it will be considerable as url. File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjava.txt"); // By using getAbsolutePath() return the complete // path of the file String abs_path = file1.getAbsolutePath(); // Display absolute path of the file object System.out.println("The absolute path of the file 1 if given path is absolute :" + " " + abs_path); // By using deleteOnExit() method to delete the file // when the virtual machine terminates file1.deleteOnExit(); System.out.println("This file will delete as soon as the virtual machine terminates"); } catch (Exception e) { System.out.println("An error occurred."); e.printStackTrace(); } } }

Output

E:\Programs>javac DeleteFileOnExit.java

E:\Programs>java DeleteFileOnExit
The absolute path of the file 1 if given path is absolute : C:\Users\computer clinic\OneDrive\Articles\myjava.txt
This file will delete as soon as the virtual machine terminates
Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.