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

如何在Groovy中创建临时文件?,groovy,temporary-files,Groovy,Temporary Files,在Java中,存在Java.io.File.createTempFile函数来创建临时文件。在Groovy中似乎不存在这样的功能,因为File类中缺少此功能。(见:) 在Groovy中是否有一种合理的方法来创建临时文件或文件路径,或者我是否需要自己创建一个临时文件或文件路径(如果我没有弄错的话,这是不容易做到的) 提前谢谢你 Groovy类扩展了Java文件类,因此可以像通常在Java中那样进行操作 File temp = File.createTempFile("temp",".scrap")

在Java中,存在Java.io.File.createTempFile函数来创建临时文件。在Groovy中似乎不存在这样的功能,因为File类中缺少此功能。(见:)

在Groovy中是否有一种合理的方法来创建临时文件或文件路径,或者我是否需要自己创建一个临时文件或文件路径(如果我没有弄错的话,这是不容易做到的)


提前谢谢你

Groovy类扩展了Java文件类,因此可以像通常在Java中那样进行操作

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

您可以在Groovy代码中使用
java.io.File.createTempFile()

def temp = File.createTempFile('temp', '.txt') 
temp.write('test')  
println temp.absolutePath
简化版 有人评论说,他们不知道如何访问创建的
文件
,因此这里有一个更简单(但功能相同)的上述代码版本

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

谢谢,效果很好,我完全忽略了尝试最简单的解决方案而不是阅读参考资料……Groovy中提供了所有JDK类和方法。值得注意的是,上面的代码片段将在每次调用时创建一个新的唯一临时文件。@Tomato刚刚花了20分钟试图理解为什么我的文件中有一大堆数字name Groovy使用
.with
闭包来清理东西,这给了Groovy额外的好处。我投了反对票,因为它没有显示如何获取新创建的文件对象。没有文件对象,我无法确定路径,也无法使用临时文件(我创建了一个临时文件,但没有任何意义)。@Benrobot我添加了一个简化版本
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