How to use the method deleteOnExit


There is a method on the java ‘File’ class named deleteOnExit.
It seems to be useful when creating tmp files. You can notify the system that you’d like the file deleted when the VM session closes.

I’m using it as follows.

object GraphViz {

  import{OutputStream, File}

  def bddView(bdd: Bdd, drawFalseLeaf: Boolean): Unit = {
    import sys.process._
    val png = bddToPng(bdd,drawFalseLeaf)
    val cmd = s"open $png"

  def bddToPng(bdd:Bdd,drawFalseLeaf: Boolean): String = {
    val png = File.createTempFile("bdd", ".png")
    val pngPath = png.getAbsolutePath
    val dot = File.createTempFile("bdd", ".dot")
    val dotPath = dot.getAbsolutePath
    bddToPng(bdd,dotPath, drawFalseLeaf)
    import sys.process._
    val cmd = s"""dot -Tpng $dotPath -o $pngPath"""
    println(s"cmd = $cmd")


I’m creating a .dot file from Scala code, then running dot graphviz from UNIX via cmd.!. This works fine. But when I run open filename as a shell comment, and the png file is not found. The problem is that the VM of the java program has already exited.

What is the correct use model which I should use here. Do I need to refactor my code to always comment out the deleteOnExit() line when running for debug purposes?


It does not notify the operating system. Instead it rather registers a shutdown hook inside a JVM. That’s why documentations says “deletion will be attempted only for normal termination of the virtual machine”:

public void deleteOnExit()

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates. Files (or directories) are deleted in the reverse order that they are registered. Invoking this method to delete a file or directory that is already registered for deletion has no effect. Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification.

Once deletion has been requested, it is not possible to cancel the request. This method should therefore be used with care.

deleteOnExit is rather not widely used. It’s unreliable, eats memory (the list of files to remove must be stored somewhere) and makes orderly JVM shutdown longer.

Depends on what you want to achieve.