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

问题描述 投票:23回答:3

在Java中存在的java.io.File.createTempFile函数来创建临时文件。在Groovy中似乎没有存在这样的功能,因为这个功能是从文件类失踪。 (参见:http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html

有没有无论如何Groovy创建一个临时文件或文件路径或做我需要建立一个自己(这是不容易得到的权利,如果我没有记错),一个理智的方法是什么?

先感谢您!

groovy temporary-files
3个回答
41
投票
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

6
投票

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

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

4
投票

在Groovy类扩展Java类文件,所以不喜欢它,你通常会用Java做的。

File temp = File.createTempFile("temp",".scrap");
temp.write("Hello world")
println temp.getAbsolutePath()  
© www.soinside.com 2019 - 2024. All rights reserved.