Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a temporary file in Groovy?

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!

like image 936
Moredread Avatar asked Dec 02 '10 17:12

Moredread


People also ask

What is a temporary file example?

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.

What is temp file in Java?

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.

How do you create a temp file in Java without the random number appended to the file?

Just check the return value of temp. createNewFile() . Read the specification of createNewFile() . The important word is atomic.


2 Answers

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 
like image 188
Dónal Avatar answered Nov 09 '22 08:11

Dónal


You can use java.io.File.createTempFile() in your Groovy code.

def temp = File.createTempFile('temp', '.txt')  temp.write('test')   println temp.absolutePath 
like image 27
An̲̳̳drew Avatar answered Nov 09 '22 07:11

An̲̳̳drew