Temporary Files And Directories in Groovy

Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

import java.nio.file.Files
import java.nio.file.Path

def check(Exception e) {
    if (e != null) {
        throw e
    }
}

// The easiest way to create a temporary file in Groovy is by
// using the Files.createTempFile method. It creates a file
// in the default temporary-file directory.
def tempFile = Files.createTempFile("sample", null)
println "Temp file name: ${tempFile}"

// Clean up the file after we're done. The OS is
// likely to clean up temporary files by itself after
// some time, but it's good practice to do this
// explicitly.
tempFile.toFile().deleteOnExit()

// We can write some data to the file.
Files.write(tempFile, [1, 2, 3, 4] as byte[])

// If we intend to write many temporary files, we may
// prefer to create a temporary directory.
// Files.createTempDirectory's arguments are similar to
// createTempFile's, but it returns a directory Path.
def tempDir = Files.createTempDirectory("sampledir")
println "Temp dir name: ${tempDir}"

tempDir.toFile().deleteOnExit()

// Now we can synthesize temporary file names by
// prefixing them with our temporary directory.
def fname = tempDir.resolve("file1")
Files.write(fname, [1, 2] as byte[])

When you run this Groovy script, you’ll see output similar to:

Temp file name: /tmp/sample8788591836951596682.tmp
Temp dir name: /tmp/sampledir3083297719083129439

In this Groovy example, we’re using the java.nio.file.Files class to create temporary files and directories. The createTempFile and createTempDirectory methods are similar to their counterparts in the original example.

We use deleteOnExit() to ensure cleanup of the temporary files and directories when the JVM exits, which is similar to the deferred cleanup in the original example.

The Files.write() method is used to write data to the files, which is a convenient way to write byte arrays in Groovy/Java.

Note that the exact paths of the temporary files and directories will vary depending on your system.