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!
Techopedia Explains Temporary File In terms of backup purposes, Microsoft's Office applications are good examples of this. For example, Microsoft Word and Excel save a temporary file associated with the current open document that it points to after a computer has recovered from a crash or power outage.
The File class in Java provides a method with name createTempFile(). This method accepts two String variables representing the prefix (starting name) and suffix(extension) of the temp file and a File object representing the directory (abstract path) at which you need to create the file.
Just check the return value of temp. createNewFile() . Read the specification of createNewFile() . The important word is atomic.
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 }
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
You can use java.io.File.createTempFile()
in your Groovy code.
def temp = File.createTempFile('temp', '.txt') temp.write('test') println temp.absolutePath
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With