【问题标题】:How do I create a temporary file in Groovy?如何在 Groovy 中创建临时文件?
【发布时间】:2011-05-19 06:59:57
【问题描述】:

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

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

提前谢谢你!

【问题讨论】:

    标签: groovy temporary-files


    【解决方案1】:
    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
    

    【讨论】:

    • 值得注意的是,上面的代码 sn -p 每次调用都会创建一个新的唯一临时文件。
    • @Tomato 花了 20 分钟试图理解为什么我的文件名中有一大堆数字
    • Groovy 使用 .with 闭包进行清理的奖励积分。
    • 我投了反对票,因为它没有显示如何获取新创建的 File 对象。没有文件对象,我无法确定路径,也无法使用临时文件(我创建了一个临时文件)。
    • @Benrobot 我加了一个简化版
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 谢谢,效果很好,我完全忽略了尝试最简单的解决方案而不是阅读参考...
      • 所有 JDK 类和方法都在 Groovy 中可用。
      猜你喜欢
      • 2010-11-04
      • 1970-01-01
      • 2012-06-14
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多