Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java File deleteOnExit() Method

Java File deleteOnExit() Method

Java File Java File


deleteOnExit() is a method in Java's java.io.File a method provided by the class, used to delete the current file when the Java Virtual Machine (JVM) terminates. This method is typically used for creating temporary files and wishing to automatically clean them up when the program exits.

Method Syntax

public

void

deleteOnExit

(

)

Method Characteristics


Use Cases

deleteOnExit() The method is especially suitable for the following situations:

Temporary file handling

When your program needs to create temporary files but wants them to be deleted automatically after the program ends:

Example

File

tempFile

=

File

.

createTempFile

(

"prefix"

,

".tmp"

)

;

tempFile.

deleteOnExit

(

)

;

 

// Delete on program exit

Resource cleanup

Ensure that created file resources are cleaned up even if the program terminates abnormally:

Example

File

logFile

=

new

File

(

"debug.log"

)

;

logFile.

deleteOnExit

(

)

;

Test environment

Create test files in unit tests and delete them automatically after the test completes:

Example

@Test

public

void

testFileOperations

(

)

throws

IOException

{

   

File

testFile

=

new

File

(

"test.txt"

)

;

    testFile.

createNewFile

(

)

;

    testFile.

deleteOnExit

(

)

;

   

// Run tests...

}


Notes

1. Not guaranteed to execute 100%

deleteOnExit() The deletion operation registered by the method is executed only when the JVM terminates normally . If the JVM crashes abnormally or is forcibly terminated, the file may not be deleted.

2. Risk of memory leak

If this method is called frequently to register a large number of files, it may cause memory problems because the JVM maintains an internal list to track these files.

3. Cannot be revoked

Once a deletion request is registered, it cannot be canceled.

4. The file must exist

If the file does not exist, calling this method has no effect.


Code Example

Basic example

Example

import

java.io.File

;

import

java.io.IOException

;

public

class

DeleteOnExitExample

{

   

public

static

void

main

(

String

[

]

args

)

{

       

try

{

           

// Create a temporary file

           

File

tempFile

=

File

.

createTempFile

(

"temp"

,

".txt"

)

;

           

System

.

out

.

println

(

"Temporary file created at: "

tempFile.

getAbsolutePath

(

)

)

;

           

           

// Register deletion request

            tempFile.

deleteOnExit

(

)

;

           

           

// Program continues with other operations...

           

System

.

out

.

println

(

"Program running, file temporarily retained..."

)

;

           

           

// Simulate program execution

           

Thread

.

sleep

(

5000

)

;

           

           

System

.

out

.

println

(

"Program about to exit, file will be deleted"

)

;

       

}

catch

(

IOException

|

InterruptedException

e

)

{

            e.

printStackTrace

(

)

;

       

}

   

}

}

Practical Application Examples

Example

import

java.io.File

;

import

java.io.FileWriter

;

import

java.io.IOException

;

public

class

LogFileExample

{

   

public

static

void

main

(

String

[

]

args

)

{

       

File

logFile

=

new

File

(

"session.log"

)

;

       

       

try

(

FileWriter

writer

=

new

FileWriter

(

logFile

)

)

{

           

// Register deletion

            logFile.

deleteOnExit

(

)

;

           

           

// Write log

            writer.

write

(

"Session started at: "

System

.

currentTimeMillis

(

)

"\n"

)

;

           

           

// Simulate program execution

           

for

(

int

i

=

0

;

i

<

5

;

i

++

)

{

                writer.

write

(

"Processing item "

i

"\n"

)

;

               

Thread

.

sleep

(

1000

)

;

           

}

           

            writer.

write

(

"Session completed\n"

)

;

       

}

catch

(

IOException

|

InterruptedException

e

)

{

            e.

printStackTrace

(

)

;

       

}

       

       

System

.

out

.

println

(

"Program ended, log file will be deleted"

)

;

   

}

}


Alternatives

Although deleteOnExit() is very convenient, but in some cases you may need to consider other alternatives:

1. try-with-resources + delete()

Example

try

(

FileWriter

writer

=

new

FileWriter

(

tempFile

)

)

{

   

// Use files

    writer.

write

(

"Some data"

)

;

}

finally

{

   

if

(

tempFile.

exists

(

)

)

{

        tempFile.

delete

(

)

;

   

}

}

2. Java 7+ Files API

Example

Path tempPath

=

Files.

createTempFile

(

"prefix"

,

".tmp"

)

;

try

{

   

// Use temporary files

    Files.

write

(

tempPath,

"Some data"

.

getBytes

(

)

)

;

}

finally

{

    Files.

deleteIfExists

(

tempPath

)

;

}

3. Use a shutdown hook

Example

Runtime

.

getRuntime

(

)

.

addShutdownHook

(

new

Thread

(

(

)

->

{

   

if

(

tempFile.

exists

(

)

)

{

        tempFile.

delete

(

)

;

   

}

}

)

)

;


Summary

deleteOnExit() The method provides a simple way to ensure file resources are cleaned up when the program exits, but it has some limitations and potential issues. When choosing to use this method, you should:

  1. Clearly understand its behavioral characteristics
  2. Consider whether delayed deletion is really needed
  3. Evaluate whether there is a better alternative
  4. Be careful not to overuse it, to avoid memory problems

For most temporary file handling scenarios, modern Java development recommends using java.nio.file.Files 's methods, which are usually more flexible and safer.

Java File Java File