在Groovy中如何创建临时文件?

27

Java中有java.io.File.createTempFile函数可以创建临时文件。但在Groovy中,似乎不存在此功能,因为File类缺少此函数。(请参见:http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html

是否存在一种合理的方式在Groovy中创建临时文件或文件路径,还是我需要自己创建(如果我没错的话,这并不容易实现)?

提前感谢你!

3个回答

47
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
}

简化版

有人评论说他们不知道如何访问创建的File,所以这里提供了一个更简单(但在功能上相同)的代码版本。

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

3
值得注意的是,上述代码片段每次被调用时都会创建一个新的唯一临时文件。 - Tomato
1
@Tomato 刚刚花了20分钟来理解为什么我的文件名里有一堆数字。 - maryokhin
4
使用.with闭包进行优美的Groovy编程,可以使代码更加简洁易读,这也是一个亮点。 - shoover
1
@Benrobot,我添加了一个简化版本。 - Dónal
为了向文件输入数据,最好使用某种写入器:.withPrintWriter { PrintWriter printWriter -> printWriter.println('the row') } - chill appreciator
显示剩余2条评论

7
您可以在Groovy代码中使用java.io.File.createTempFile()
def temp = File.createTempFile('temp', '.txt') 
temp.write('test')  
println temp.absolutePath

5
Groovy类扩展了Java文件类,因此您可以像在Java中一样进行操作。
File temp = File.createTempFile("temp",".scrap");
temp.write("Hello world")
println temp.getAbsolutePath()  

谢谢,那个方法运行得非常完美,我完全忽略了尝试最简单的解决方案,而不是去阅读参考资料... - Moredread
1
所有的JDK类和方法都可以在Groovy中使用。 - Dónal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接