开发者

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 (wh开发者_如何学编程ich 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()  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜