How do I create a temporary file in Groovy?
You can use java.io.File.createTempFile()
in your Groovy code.
def temp = File.createTempFile('temp', '.txt')
temp.write('test')
println temp.absolutePath
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