Android Create Temp File In Cache Directory (Kotlin)

Apr 13, 2018

Create a file in cache directory

// create file in cache directoryval outputFile = File(context.cacheDir, "output.txt")

Create a file in cache directory including date & time in filename.

val timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-kkmmss"))val outputFile = File(context.cacheDir, "output-${timestamp}.txt")

Create a temp file in cache directory.

val timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-kkmmss"))val outputFile = File.createTempFile(timestamp, null, context.cacheDir);

You might want to delete output file if already exist and create the necessary directory before usage.

if (outputFile.exists()) {    outputFile.delete()}else {    outputFile.parentFile?.mkdirs()}

Write single large string output to file.

val input = "I am String"val inputStream = ByteArrayInputStream(input.toByteArray(UTF_8))val outputStream = FileOutputStream(outputFile)// the following should work as well // val outputStream = outputFile.outputStream()inputStream.use { input ->    outputStream.use { output ->        input.copyTo(output)    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.