The file won't be deleted automatically. See File.createTempFile:

This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.

So you have to explicitly call File.deleteOnExit():

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

Answer from Kai on Stack Overflow
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › java › FIO03-J.+Remove+temporary+files+before+termination
FIO03-J. Remove temporary files before termination - SEI CERT Oracle Coding Standard for Java - Confluence
This is the only method from Java 6 and earlier that is designed to produce unique file names, although the names produced can be easily predicted. A random number generator can be used to produce the prefix if a random file name is required. This example also uses the deleteOnExit() method to ...
Top answer
1 of 6
122

The file won't be deleted automatically. See File.createTempFile:

This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.

So you have to explicitly call File.deleteOnExit():

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

2 of 6
65

As the other answers note, temporary files created with File.createTempFile() will not be deleted automatically unless you explicitly request it.

The generic, portable way to do this is to call .deleteOnExit() on the File object, which will schedule the file for deletion when the JVM terminates. A slight disadvantage of this method, however, is that it only works if the VM terminates normally; on an abnormal termination (i.e. a VM crash or forced termination of the VM process), the file might remain undeleted.

On Unix-like systems (such as Linux), it's actually possible to obtain a somewhat more reliable solution by deleting the temporary file immediately after opening it. This works because Unix filesystems allow a file to be deleted (unlinked, to be precise) while it's still held open by one or more processes. Such files can be accessed normally through the open filehandle, and the space they occupy on disk will only be reclaimed by the OS after the last process holding an open handle to the file exits.

So here's the most reliable and portable way I know to ensure that a temporary file will be properly deleted after the program exits:

import java.io.File;
import java.io.RandomAccessFile;
import java.io.IOException;
 
public class TempFileTest
{
    public static void main(String[] args)
    {
        try {
            // create a temp file
            File temp = File.createTempFile("tempfiletest", ".tmp"); 
            String path = temp.getAbsolutePath();
            System.err.println("Temp file created: " + path);

            // open a handle to it
            RandomAccessFile fh = new RandomAccessFile (temp, "rw");
            System.err.println("Temp file opened for random access.");

            // try to delete the file immediately
            boolean deleted = false;
            try {
                deleted = temp.delete();
            } catch (SecurityException e) {
                // ignore
            }

            // else delete the file when the program ends
            if (deleted) {
                System.err.println("Temp file deleted.");
            } else {
                temp.deleteOnExit();
                System.err.println("Temp file scheduled for deletion.");
            }

            try {
                // test writing data to the file
                String str = "A quick brown fox jumps over the lazy dog.";
                fh.writeUTF(str);
                System.err.println("Wrote: " + str);

                // test reading the data back from the file
                fh.seek(0);
                String out = fh.readUTF();
                System.err.println("Read: " + out);

            } finally {
                // close the file
                fh.close();
                System.err.println("Temp file closed.");
            }

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

On a Unix-like system, running this should produce something like the following output:

Temp file created: /tmp/tempfiletest587200103465311579.tmp
Temp file opened for random access.
Temp file deleted.
Wrote: A quick brown fox jumps over the lazy dog.
Read: A quick brown fox jumps over the lazy dog.
Temp file closed.

Whereas on Windows, the output looks slightly different:

Temp file created: C:\DOCUME~1\User\LOCALS~1\Temp\tempfiletest5547070005699628548.tmp
Temp file opened for random access.
Temp file scheduled for deletion.
Wrote: A quick brown fox jumps over the lazy dog.
Read: A quick brown fox jumps over the lazy dog.
Temp file closed.

In either case, however, the temp file should not remain on the disk after the program has ended.


PS. While testing this code on Windows, I observed a rather surprising fact: apparently, merely leaving the temp file unclosed is enough to keep it from being deleted. Of course, this also means that any crash that happens while the temp file is in use will cause it to be left undeleted, which is exactly what we're trying to avoid here.

AFAIK, the only way to avoid this is to ensure that the temp file always gets closed using a finally block. Of course, then you could just as well delete the file in the same finally block too. I'm not sure what, if anything, using .deleteOnExit() would actually gain you over that.

🌐
Mkyong
mkyong.com › home › java › how to delete a temporary file in java
How to delete a temporary file in Java - Mkyong.com
July 21, 2020 - package com.mkyong.io.temp; import java.io.File; import java.io.IOException; public class TempFileDelete2 { public static void main(String[] args) { try { File tempFile = File.createTempFile("abc_", ".log"); System.out.println(tempFile); boolean result = tempFile.delete(); if (result) { System.out.println(tempFile.getName() + " is deleted!"); } else { System.out.println("Sorry, unable to delete the file."); } // delete when JVM exit normally.
🌐
How to do in Java
howtodoinjava.com › home › i/o › java delete temporary file
Java Delete Temporary File
April 14, 2022 - Once deletion has been requested, it is not possible to cancel the request. File temp; try { temp = File.createTempFile("myTempFile", ".txt"); temp.deleteOnExit(); //Delete when JVM exits //Perform other operations } catch (IOException e) { ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-delete-temporary-file-in-java
How to Delete Temporary File in Java? - GeeksforGeeks
August 5, 2021 - If your code terminates abnormally then keep in mind that your temporary file has not been deleted yet and once you have requested for the delete operation then you can't cancel afterwards. ... // Delete File when JVM Exists import java.io.File; import java.io.IOException; public class tempFile { public static void main(String[] args) { File temp; try { // name of the file and extension temp = File.createTempFile("TempFile", ".txt"); // Delete when JVM exits temp.deleteOnExit(); } // If not found any temporary file catch (IOException e) { e.printStackTrace(); } } }
🌐
Alvin Alexander
alvinalexander.com › java › java-temporary-files-create-delete
Java temporary file: How to create and delete temporary files | alvinalexander.com
November 8, 2021 - Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification." I hope this Java temporary file tutorial has been helpful. As you've seen, just use createTempFile to create a temporary file in Java, and then use deleteOnExit if you ...
🌐
Tutorialspoint
tutorialspoint.com › java › io › file_deleteonexit.htm
Java - File deleteOnExit() method
package com.tutorialspoint; import ...bsolutePath()); // Mark the file to be deleted on JVM exit tempFile.deleteOnExit(); System.out.println("File will be deleted on exit."); } else { System.out.println("File already exists."); } ...
Find elsewhere
Top answer
1 of 6
64

Temporary directories created by Files.createTempDirectory() are not deleted upon system exit (JVM termination), unless you configure them to do so:

A shutdown-hook, or the File.deleteOnExit() mechanism may be used to delete the directory automatically.

Meaning you could call:

Path tmp = Files.createTempDirectory(null);
tmp.toFile().deleteOnExit();

However you cannot delete a directory unless it's empty, as document by File.delete():

Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

So we need to get a bit fancier if you want the directory and its contents deleted. You can recursively register a directory and its children for deletion like so:

public static void recursiveDeleteOnExit(Path path) throws IOException {
  Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file,
        @SuppressWarnings("unused") BasicFileAttributes attrs) {
      file.toFile().deleteOnExit();
      return FileVisitResult.CONTINUE;
    }
    @Override
    public FileVisitResult preVisitDirectory(Path dir,
        @SuppressWarnings("unused") BasicFileAttributes attrs) {
      dir.toFile().deleteOnExit();
      return FileVisitResult.CONTINUE;
    }
  });
}

Take note however, this registers all currently existing files for deletion - if after calling this method you create new files, they and their parent directories will not be deleted per the documented behavior of File.delete().

If you want to delete a directory upon exit, regardless of the contents of said directory, you can use a shutdown-hook in an almost identical manner:

public static void recursiveDeleteOnShutdownHook(final Path path) {
  Runtime.getRuntime().addShutdownHook(new Thread(
    new Runnable() {
      @Override
      public void run() {
        try {
          Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file,
                @SuppressWarnings("unused") BasicFileAttributes attrs)
                throws IOException {
              Files.delete(file);
              return FileVisitResult.CONTINUE;
        }
        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException e)
            throws IOException {
          if (e == null) {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
          }
          // directory iteration failed
          throw e;
        }
        });
      } catch (IOException e) {
        throw new RuntimeException("Failed to delete "+path, e);
      }
    }}));
}

Note however that calling this repeatedly registers a new shutdown thread each time, which could potentially cause problems at scale. File.deleteOnExit() stores a set of registered files, and deletes all of them in one shutdown hook. If you need to delete many directories in this manner, you'd want to implement something similar.

2 of 6
27

As per the API, no it doesn't, you need to manually remove the directory, using file.deleteOnExit() method.

As with the createTempFile methods, this method is only part of a temporary-file facility. A shutdown-hook, or the File.deleteOnExit() mechanism may be used to delete the directory automatically.

Top answer
1 of 3
48

Short Answer

You can't delete arbitrary files in Java NIO, but you can use the StandardOpenOption.DELETE_ON_CLOSE when opening a new stream, which will delete the file as soon as the stream closes, either by calling .close() (including from a try-with-resources statement) or the JVM terminating. For instance:

Files.newOutputStream(Paths.get("Foo.tmp"), StandardOpenOption.DELETE_ON_CLOSE);

Long Answer

After a great deal of digging around, I found that Java NIO does have a way to delete on exit, but it approaches it in a different way that Java I/O.

First off, the Javadoc for Files.createTempFile() describes three ways to delete files:

Where used as a work files [sic], the resulting file may be opened using the DELETE_ON_CLOSE option so that the file is deleted when the appropriate close method is invoked. Alternatively, a shutdown-hook, or the File.deleteOnExit() mechanism may be used to delete the file automatically.

The last choice, File.deleteOnExit() is of course a Java I/O method, which we are trying to avoid. A shutdown-hook is what is happening behind the scenes when you call the aforementioned method. But the DELETE_ON_CLOSE option is pure Java NIO.

Rather than deleting arbitrary files, Java NIO assumes that you are only interested in deleting files that you are actually opening. Therefore, methods that create a new stream such as Files.newOutputStream() can optionally take several OpenOptions, where you can input StandardOpenOption.DELETE_ON_CLOSE. What that does is delete the file as soon as the stream is closed (either by a call to .close() or the JVM exiting).

For instance:

Files.newOutputStream(Paths.get("Foo.tmp"), StandardOpenOption.DELETE_ON_CLOSE);

...will delete the file associated with the stream when the stream is closed, either from an explicit call to .close(), the stream being closed as part of a try-with-resources statement, or the JVM terminating.

Update: On some operating systems such as Linux, StandardOpenOption.DELETE_ON_CLOSE deletes as soon as the OutputStream is created. If all you need is one OutputStream, that may still be okay. See DELETE_ON_CLOSE deletes files before close on Linux for more info.

So Java NIO adds new functionality over Java I/O in that you can delete a file when closing a stream. If that's a good enough alternative to deleting during JVM exit, you can do it in pure Java NIO. If not, you'll have to rely on Java I/O's File.deleteOnExit() or a shutdown-hook to delete the file.

2 of 3
31

Behind the scenes, File.deleteOnExit() will just create a shutdown hook via Runtime.addShutdownHook().

Then, you can do the same thing with NIO:

Runtime.getRuntime().addShutdownHook(new Thread() {
  public void run() {
    Path path = ...;

    Files.delete(path);
  }
});
🌐
GitHub
gist.github.com › ato › 6774390
TempDirectory java temporary directory delete on exit · GitHub
TempDirectory java temporary directory delete on exit - TempoDirectory.java
🌐
Stack Overflow
stackoverflow.com › questions › 42175947 › temp-file-wont-delete-on-exit-why-is-this › 42403266
java - Temp file won't delete on exit - why is this? - Stack Overflow
if (temp != null) { for (File file : temp.listFiles()) { if (file.getName().contains("JNative") || file.getName().contains("rar") || file.getName().contains("hsper") || file.getName().contains("jna") || file.getName().contains("dll")) { file.deleteOnExit(); System.out.println(file.getName()); } } } The "duplicate" question refers to deleting files that you have created - I haven't created these temp.
🌐
DevX
devx.com › home › clean up your mess: managing temp files in java apps
Clean Up Your Mess: Managing Temp Files in Java Apps - DevX
April 30, 2026 - Performing the steps in this order ensures that there is no race condition allowing another manager to delete the temp directory before the lock is created. The lock file is marked for deletion at exit, which will work since nothing in the JVM ...
🌐
InfoWorld
infoworld.com › home › software development › programming languages › java
Automatic Deletion of Temporary Work Files in Java 7/Groovy | InfoWorld
August 7, 2011 - In this case, the body of the thread is very simple, using a single statement taking advantage of Java 7’s Files.delete(Path) method. ... Scripts commonly need to create files for temporary use and Java now provides several easy approaches for ensuring automatic deletion of files meant to be temporary in nature and to be removed when the particular script or application is finished.
🌐
LabEx
labex.io › tutorials › java-how-to-use-temporary-file-deletion-in-java-419558
How to use temporary file deletion in Java | LabEx
public class AutomaticDeletionExample { public static void main(String[] args) { File tempFile = File.createTempFile("labex_", ".tmp"); // Mark file for automatic deletion when JVM exits tempFile.deleteOnExit(); } } import java.nio.file.Files; import java.nio.file.Path; public class NIODeletionExample { public static void main(String[] args) { try { Path tempPath = Files.createTempFile("labex_", ".txt"); // Delete file immediately Files.delete(tempPath); } catch (IOException e) { e.printStackTrace(); } } }
🌐
javaspring
javaspring.net › java_io › java_file_deleteonexit_method_a_comprehensive_guide
Java - File deleteOnExit() Method: A Comprehensive Guide
Then we call deleteOnExit() on the tempFile object. This schedules the file to be deleted when the JVM exits. We can then perform any necessary operations on the file before the program exits.
🌐
Antkorwin
antkorwin.com › gc › autodeletable_temp_files_in_java_eng.html
Automaticaly deleted temporary files in Java (based on PhantomReferences)
March 10, 2021 - We need something to track all references to the file because we can delete a file from the disk exactly after all references will be collected by GC. Using PhantomReference can help us, when the reference is dequeued from the queue we can delete a file. Let’s extend the PhantomReference class to add a path to the temporary file and method to delete the file from the disk: