How do I create a temporary file in Groovy?

Moredread picture Moredread · Dec 2, 2010 · Viewed 20.6k times · Source

In Java there exists the java.io.File.createTempFile function to create temporary files. In Groovy there doesn't seem to exist such a functionality, as this function is missing from the File class. (See: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html)

Is there a sane way to create a temporary file or file path in Groovy anyhow or do I need to create one myself (which is not easy to get right if I'm not mistaken)?

Thank you in advance!

Answer

Dónal picture Dónal · Dec 3, 2010
File.createTempFile("temp",".tmp").with {
    // Include the line below if you want the file to be automatically deleted when the 
    // JVM exits
    // deleteOnExit()

    write "Hello world"
    println absolutePath
}

Simplified Version

Someone commented that they couldn't figure out how to access the created File, so here's a simpler (but functionally identical) version of the code above.

File file = File.createTempFile("temp",".tmp")
// Include the line below if you want the file to be automatically deleted when the 
// JVM exits
// file.deleteOnExit()

file.write "Hello world"
println file.absolutePath