简体   繁体   中英

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!

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

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

def temp = File.createTempFile('temp', '.txt') 
temp.write('test')  
println temp.absolutePath

The Groovy classes extend the Java file class so do it like you would normally do in Java.

File temp = File.createTempFile("temp",".scrap");
temp.write("Hello world")
println temp.getAbsolutePath()  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM