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

Mor*_*ead 23 groovy temporary-files

在Java中,存在用于创建临时文件的java.io.File.createTempFile函数.在Groovy中似乎没有这样的功能,因为File类中缺少此函数.(见:http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html)

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

先感谢您!

Dón*_*nal 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
}
Run Code Online (Sandbox Code Playgroud)

简化版

有人评论说他们无法弄清楚如何访问创建的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
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,上面的代码片段每次调用时都会创建一个新的唯一临时文件. (3认同)
  • Groovy使用`.with`闭包来清理东西的加分点. (3认同)

An̲*_*rew 6

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

def temp = File.createTempFile('temp', '.txt') 
temp.write('test')  
println temp.absolutePath
Run Code Online (Sandbox Code Playgroud)


Jar*_*red 5

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

File temp = File.createTempFile("temp",".scrap");
temp.write("Hello world")
println temp.getAbsolutePath()  
Run Code Online (Sandbox Code Playgroud)