TemporaryDirectory

class TemporaryDirectory(prefix: String? = null, parent: File = File(checkNotNull(System.getProperty("java.io.tmpdir")) { "java.io.tmpdir is not set" })) : AutoCloseable(source)

An independently owned scratch directory with a unique name, so parallel tests never share state.

Cleanup is explicit: call remove when the test finishes, for example in a finally block or an @After method, so a directory can outlive a single call when needed.

val directory = TemporaryDirectory(prefix = "ImportTests")
try {
val file = directory.write("{}".encodeToByteArray(), "fixtures/empty.json")
importer.import(file)
} finally {
directory.remove()
}

It is also AutoCloseable, so use { } removes it when the block ends:

TemporaryDirectory(prefix = "ImportTests").use { directory ->
importer.import(directory.write("{}", "fixtures/empty.json"))
}

Parameters

prefix

An optional label placed before the unique name, such as a test name, to identify leftover directories. It must be nonempty and must not contain a path separator.

parent

The directory to create it in; defaults to java.io.tmpdir.

Throws

for an unusable prefix.

when the directory cannot be created.

Constructors

Link copied to clipboard
constructor(prefix: String? = null, parent: File = File(checkNotNull(System.getProperty("java.io.tmpdir")) { "java.io.tmpdir is not set" }))

Properties

Link copied to clipboard
val file: File

The unique directory.

Functions

Link copied to clipboard
open override fun close()

Removes the directory and its contents, like remove, so use { } cleans up. Closing twice is harmless.

Link copied to clipboard
fun remove()

Removes the directory and its contents. Removing an already-removed directory is harmless.

Link copied to clipboard
fun write(bytes: ByteArray, name: String): File

Writes a file beneath this directory, creating parent folders.

fun write(text: String, name: String): File

Writes UTF-8 text beneath this directory, creating parent folders.