1. Why writeText() is sometimes dangerous
When you first start saving data to a file, it feels like the problem is solved forever: “well, I called file.writeText(text) — so the file is written”. But a file system is not a function; it’s a separate little world with its own rules. And that world sometimes throws surprises: an unexpected process termination, running out of disk space, power loss, an antivirus that “paused”, or someone simply yanked out a flash drive (yes, it happens).
The problem is not that writeText() is “bad”. The problem is that overwriting the target file directly can leave the file in an intermediate state. For example, you stored your app data in data/expenses.txt, started writing a new version — and in the middle of the write everything crashed. As a result, the file can become empty or only partially written. And the worst part: on the next launch you’ll try to read it and find “half a line” or a truncated chunk.
Imagine your file is a notebook with homework. Direct overwrite is like erasing the old answer and then suddenly falling asleep face-first on the notebook mid-way. In the morning you have neither the old solution nor the new one. The atomic write approach is when you write the new homework on a draft sheet, and then neatly paste the finished page into the notebook.
A small demo of “how we usually write” (and why it’s risky when failures happen):
import java.io.File
fun main() {
val target = File("data/expenses.txt")
target.writeText("...new data...\n")
println("Saved!") // Saved!
}
From the code’s point of view, everything looks nice. From real life’s point of view, a lot can happen between the start and the end of the write.
2. The atomic write idea: temp → rename
Now we’ll go through a simple protocol that applications very often use to reduce the risk of a “partial write”. I’m deliberately describing it in plain terms, because truly “strictly atomic on all OSes and file systems under any conditions” is deeper and more complex. For this course, it’s important to master a practical and noticeably more reliable approach without magic and without diving into low-level details.
The idea is: we don’t touch the target file until the new version is fully ready. First, write the entire text into a temporary file (temp) next to the target. If writing the temp succeeded, then we “publish” the result: rename the temp into the target. If something crashes in the middle of writing the temp, the target file remains the old one—intact and readable.
Process diagram (as a mini-algorithm):
flowchart TD
A[Built the new text] --> B[Wrote it to a temp file next to the target]
B -->|success| C[Published: rename temp -> target]
B -->|error| D[Left target as it was]
C --> E[Deleted leftover temp files, if any]
D --> E
The key meaning here is: “build the new result separately, then swap quickly”. Quickly matters because the less “time in the danger zone”, the lower the chance of ending up in an intermediate state.
3. Why the temp file must be created next to the target file
When you hear “temporary file”, your hand reaches to write it somewhere “in /tmp”, “in the current directory”, or “in a separate temp folder”. And sometimes that’s a perfectly fine idea. But in our protocol there’s an important nuance: renameTo() behaves much more predictably when the temp file is in the same directory as the target.
For a beginner this can look like a weird nitpick (“what difference does it make where the file is if I’m renaming it?”), but in practice there is a difference. If the temp is on another disk/partition/file system, a rename can turn into a “move”, and a move is no longer required to be fast and reliable. And sometimes it just won’t work, and renameTo() will honestly return false.
We don’t need to dive into OS internals right now. Let’s remember a practical rule: create the temp file in the same folder where the target file will be. Then you have fewer chances to get false from renameTo() and more chances that “publishing” will work as intended.
Let’s make a small utility that builds the temp path next to the target:
import java.io.File
fun tempFor(target: File): File {
val parent = target.parentFile ?: File(".")
return File(parent, target.name + ".tmp")
}
Yes, the .tmp name is quite simple. In real apps, people often add a random suffix to avoid conflicts, but for a learning project we’ll start with the straightforward option.
4. renameTo() and checking the result
Renaming sounds like a “rock-solid operation”, but the JVM method File.renameTo(...) has an important property: it returns a Boolean. That means the operation can fail—and you won’t necessarily get an exception automatically (it depends on the situation and platform). So our code must treat renameTo() as a step that must be checked.
It’s very easy to make a thinking mistake here: “well, there’s no exception, so everything is fine”. No, it isn’t. You must check true/false and decide what to do.
Mini example of the correct style:
import java.io.File
fun main() {
val from = File("data/a.tmp")
val to = File("data/a.txt")
val renamed = from.renameTo(to)
println("renamed=$renamed") // renamed=true (or false)
}
If renamed=false, that’s not a “minor inconvenience”; it’s a signal that publishing did not happen. And if at that moment you delete the temp file “just in case”, you might delete the only up-to-date version of your data.
5. Implementing atomicWriteText: the protocol and nuances
Direct write vs temp+rename
Before writing the full code, it helps to capture the difference between the approaches not as “feelings”, but as expected behavior under failures.
| Situation | Direct overwrite of target | Temp → rename |
|---|---|---|
| Error during write (disk full, process died) | target may become partially written | target remains the old version |
| Error during “publishing” | usually too late: target may already be affected | the swap might not happen, but you still have temp |
| Diagnostics | “why is the file corrupted?”—an unpleasant quest | easier to see which step failed |
| Implementation | easier in 1 line | a bit more code, but you sleep better |
This doesn’t make direct writing “forbidden”. It just means you now have a tool for cases where the file is important.
Basic function version
Now we’ll assemble an atomicWriteText function that implements the protocol:
- ensure the folder for the target exists (or create it)
- write the new text into temp
- if the target already exists, decide what to do (in this lecture: a simple policy—delete it so it doesn’t block rename)
- perform renameTo(temp -> target) and check the result
- in any case, attempt to clean up temp (best effort) in finally
What matters here is that finally is our “stage cleaner”: it runs both on success and on failure. Kotlin (and the JVM) guarantee running finally when exiting try (with rare exotic exceptions), so it’s a great tool for cleanup.
The first function version will be as clear as possible, without “beauty optimizations”:
import java.io.File
import java.io.IOException
fun atomicWriteText(target: File, text: String): Boolean {
val parent = target.parentFile ?: File(".")
if (!parent.exists() && !parent.mkdirs()) return false
val temp = File(parent, target.name + ".tmp")
return try {
temp.writeText(text)
if (target.exists() && !target.delete()) return false
temp.renameTo(target)
} catch (e: IOException) {
false
} finally {
if (temp.exists()) temp.delete() // best effort
}
}
Notice an important “psychological point”: finally is not a “100% guarantee to delete temp”, because delete() can fail too. But we don’t need an absolute guarantee: what we need is not to leave temporary files behind in common failure cases, as much as possible.
Improve readability: small helper functions
When a function starts doing many small checks, a beginner often falls into one of two extremes: either they write everything in one huge block and get confused, or they split it into dozens of micro-functions and lose the thread. We’ll pick the golden middle: extract the most “speaking” parts into helpers so the main protocol reads like a story.
By the way, Kotlin encourages “expressions instead of ceremonies”, and try can also be an expression, meaning it can return a value—that’s normal and readable.
Let’s make directory preparation a separate function:
import java.io.File
fun ensureParentDir(target: File): Boolean {
val parent = target.parentFile ?: File(".")
if (parent.exists()) return parent.isDirectory
return parent.mkdirs()
}
And temp generation next to the target:
import java.io.File
fun tempFor(target: File): File {
val parent = target.parentFile ?: File(".")
return File(parent, target.name + ".tmp")
}
Now the main protocol can be rewritten a bit more readably:
import java.io.File
import java.io.IOException
fun atomicWriteText(target: File, text: String): Boolean {
if (!ensureParentDir(target)) return false
val temp = tempFor(target)
return try {
temp.writeText(text)
if (target.exists() && !target.delete()) return false
temp.renameTo(target)
} catch (e: IOException) {
false
} finally {
if (temp.exists()) temp.delete()
}
}
It’s still the same algorithm; now it’s just easier to explain in plain language.
Deleting the target before rename: a trade-off
You may have noticed this line:
if (target.exists() && !target.delete()) return false
It’s a simple policy: if the file already exists, we delete it so that renameTo can “take its place”. On some platforms, renaming over an existing file works; on others it doesn’t, so for a learning project we make the behavior more predictable.
But there’s a trade-off. If you delete the target and then renameTo() fails, you can end up in a “the old is gone, the new isn’t published” situation. We partially reduce the risk by deleting the target after successfully writing temp, not before. But there is still a window where the old file is already deleted.
In this lecture, we lock in the basic temp→rename protocol and careful check discipline. If you additionally need to protect the old data version, you need a separate mechanism that preserves the previous file before replacing it. That’s a separate topic, and we won’t go into it here.
Why try should be narrow
Another common trap is wrapping absolutely everything in try: building the text, formatting, parsing, printing messages. Then you catch IOException, but the actual error might not be I/O at all, and you lose clarity about what exactly failed.
The idea of a narrow try/catch is: put inside only what actually touches the file system. Everything else lives outside. This style also matches the general recommendation to keep expressions (try, if, when) readable: let them return a value and not grow into a “pile of everything at once”.
So this is fine:
val text = lines.joinToString("\n", postfix = "\n")
val ok = atomicWriteText(out, text)
But this is already questionable:
try {
val text = lines.joinToString("\n", postfix = "\n")
out.writeText(text)
println("ok")
} catch (e: Exception) {
println("something went wrong")
}
In the second version you “caught everything”, but you threw away the meaning.
6. Integrating atomic write into a console application
So the examples aren’t “in a vacuum”, let’s continue the practical idea of the learning app: a console expense tracker. Suppose that by this point in the course you already have a list of expenses in memory and simple commands (add/list). Keeping them only in RAM is sad: close the program—and everything is gone. So we persist data to a text file.
Let the format be simple: one line—one record like 2026-01-14;Coffee;4.50. The format isn’t perfect, but the goal right now is not the format; it’s reliable publishing of the file.
Let’s make a function to assemble a line for saving (no complex formats):
fun formatExpenseLine(date: String, title: String, amount: Double): String {
return "$date;$title;$amount"
}
Now a function to save the expense list into a file. Note: we first build the entire text in memory, and only then write it “atomically” via temp+rename. This is important: if you write “piece by piece” into the target, you’re back to the partial write problem.
import java.io.File
fun saveExpenses(target: File, lines: List<String>): Boolean {
val text = lines.joinToString(separator = "\n", postfix = "\n")
return atomicWriteText(target, text)
}
And a mini-main example that saves two expenses:
import java.io.File
fun main() {
val out = File("data/expenses.txt")
val lines = listOf(
formatExpenseLine("2026-01-14", "Coffee", 4.50),
formatExpenseLine("2026-01-14", "Sandwich", 8.00)
)
val ok = saveExpenses(out, lines)
println("saved=$ok") // saved=true (if everything succeeded)
}
Even if the program crashes in the middle of writing the temp file, the old expenses.txt should not turn into a “truncated chunk”. That’s the practical benefit of the protocol.
7. Common mistakes
Mistake #1: writing the temp file not next to the target.
Beginners often write temp into the current directory, while the target is in data/out/.... Then renameTo() suddenly returns false, and “shamanism” begins: “but I’m renaming it, why can’t it?”. Within our protocol, it’s simpler and more reliable to create temp in the same folder as the target so publishing is more predictable.
Mistake #2: not checking the result of renameTo(...).
A very common scenario: someone writes temp.renameTo(target) and immediately prints “Saved!”. If renameTo returned false, you effectively lied to yourself and the user, and then you might also delete temp in finally, losing fresh data. The rule is simple: renameTo is a step of the algorithm; its result must be checked.
Mistake #3: deleting the target before successfully writing temp.
Sometimes the code looks like: “first I’ll delete the old file, then I’ll write the new one”. That brings us back to the worst-case scenario: if writing the new file fails, the old one is already gone. In our protocol the order matters: first fully write temp, and only then decide what to do with the target.
Mistake #4: forgetting to clean up the temporary file.
If you don’t use finally, then on an exception the temp file will remain on disk. Once is not scary, but over time the folder can turn into a museum of .tmp artifacts. finally is a normal tool specifically for such cleanup actions, and it is guaranteed to execute when exiting try regardless of whether there was an exception.
Mistake #5: doing an “atomic write”, but writing in chunks directly to temp without guaranteeing completeness.
Sometimes people try to write temp line by line and in parallel update some parts of the file. By itself this isn’t forbidden, but then you must be sure that temp is either written to the end, or you treat it as garbage. The clearest path for a learning project is to assemble all text into a string and write it in one shot. It’s easier to read and easier to debug.
Mistake #6: catching Exception “just in case” and returning true.
The most dangerous variant: “if there’s an error—oh well, we’ll still say we saved”. This guarantees data loss, and you’ll only find out from the user (who, as we know, “did everything correctly”). It’s better to return false and honestly report that saving failed than to pretend everything is fine.
GO TO FULL VERSION