Temporary files
suggest changeTemporary files and directories allow applications to buffer large uploads, stage intermediate pipeline processing (such as image or PDF rendering), cache calculations, and isolate unit test fixtures without polluting persistent storage.
Kotlin offers modern standard library extensions in kotlin.io.path alongside traditional java.io.File and java.nio.file.Files utilities.
Creating Temporary Files and Directories (kotlin.io.path)
The idiomatic way to handle temporary files in modern Kotlin is via kotlin.io.path.*:
import kotlin.io.path.createTempFile
import kotlin.io.path.createTempDirectory
import kotlin.io.path.writeText
import kotlin.io.path.readText
import kotlin.io.path.deleteIfExists
fun main() {
// Create a temporary file with custom prefix and suffix
val tempFile = createTempFile(prefix = "report_", suffix = ".csv")
println("Created temp file: ${tempFile.toAbsolutePath()}")
try {
// Write and read data
tempFile.writeText("id,name,role\n1,Alice,Admin\n2,Bob,User")
val content = tempFile.readText()
println("File content:\n$content")
} finally {
// Explicitly clean up file
tempFile.deleteIfExists()
println("Temporary file deleted successfully.")
}
// Create a temporary directory
val tempDir = createTempDirectory(prefix = "batch_job_")
println("Created temp directory: ${tempDir.toAbsolutePath()}")
try {
val nestedFile = tempDir.resolve("chunk_01.dat")
nestedFile.writeText("binary chunk data")
} finally {
// Clean up entire directory tree
tempDir.toFile().deleteRecursively()
println("Temporary directory deleted successfully.")
}
}
Scoped Automatic Cleanup with Higher-Order Functions
To prevent disk leaks in long-running services when exceptions occur, wrap temporary file creation in a self-cleaning extension function:
import java.nio.file.Path
import kotlin.io.path.createTempFile
import kotlin.io.path.deleteIfExists
inline fun <R> withTempFile(
prefix: String = "tmp",
suffix: String? = null,
block: (Path) -> R
): R {
val file = createTempFile(prefix, suffix)
return try {
block(file)
} finally {
file.deleteIfExists()
}
}
fun processUploadedData(rawBytes: ByteArray): Long {
return withTempFile(prefix = "upload_", suffix = ".bin") { path ->
java.nio.file.Files.write(path, rawBytes)
// Perform processing, e.g., compute file size or checksum
java.nio.file.Files.size(path)
}
}
Using java.io.File.createTempFile and deleteOnExit
For legacy codebases or simple scripts, File.createTempFile remains available:
import java.io.File
fun createLegacyTempFile(): File {
val file = File.createTempFile("preview_", ".tmp")
// Register deletion when the JVM terminates normally
file.deleteOnExit()
file.writeText("Temporary cache payload")
return file
}
Warning:
deleteOnExit()only runs when the JVM shuts down normally. For long-running servers, relying ondeleteOnExit()will leak disk space over time. Always delete temporary files explicitly once processing completes.
Unit Testing with JUnit 5 @TempDir
In unit and integration tests, JUnit 5 provides the @TempDir annotation to automatically generate and tear down temporary directories per test method or test class:
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
import kotlin.io.path.writeText
import kotlin.io.path.readText
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class FileProcessorTest {
@Test
fun testFileWritingAndReading(@TempDir tempDir: Path) {
val testFile = tempDir.resolve("sample.txt")
testFile.writeText("Kotlin Documentation")
assertTrue(testFile.toFile().exists())
assertEquals("Kotlin Documentation", testFile.readText())
// JUnit automatically deletes tempDir when the test finishes
}
}
Security: Restricting POSIX File Permissions
On shared servers or multi-tenant UNIX environments, the system temporary directory (/tmp) is accessible by other OS users. You can restrict permissions to owner-only using POSIX file attributes:
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermissions
fun createSecureTempFile(prefix: String, suffix: String): Path {
val ownerOnlyAttrs = PosixFilePermissions.asFileAttribute(
PosixFilePermissions.fromString("rw-------") // 0600: read/write only for owner
)
return try {
Files.createTempFile(prefix, suffix, ownerOnlyAttrs)
} catch (e: UnsupportedOperationException) {
// Fallback for non-POSIX filesystems (like Windows NTFS)
Files.createTempFile(prefix, suffix)
}
}
Best Practices
- Always delete in a
finallyblock: Wrap temporary operations intry-finallyor scoped lambda helpers to guarantee cleanup if parsing or network calls fail. - Do not rely on
deleteOnExit()in web services: The JVM may stay up for months; temporary files will accumulate until the disk fills up. - Specify sensible prefixes and extensions: Meaningful prefixes (e.g.
pdf_export_) help system administrators inspect rogue processes during incident response. - Set POSIX permissions for sensitive data: If temporary files contain tokens, credentials, or personal user data, set
rw-------permissions on POSIX systems.