1. Partial file and result publication
If files were honest, they would simply disappear when something goes wrong. But reality is harsher: after an error, power loss, disk-full situation, or coroutine cancellation, we might end up with a file that exists, has a size greater than zero, sometimes even opens… and still contains only part of the data. Such a “half-file” is especially dangerous because it looks like a normal program result.
Imagine two scenarios. In the first, you generate a report report.txt and write it directly. The user sees the file, opens it—there is truncated text, but no explicit error. In the second, you copy a large file and interrupt the process—if you were writing directly to the final path, you now have a “ready” file that is actually corrupted. And this is where fun quests start at the level of “why does my archive sometimes break”.
Almost always it is better to follow a rule: a result is considered published only after the operation successfully completes, and until then it must live in a “draft” (temp/part). That is exactly the mechanism we are going to build.
Publication strategy: temp → rename → cleanup
In this topic, it is important to put the terminology in order, because it genuinely helps you think. There is the action “do the work” (write bytes/text), and there is the action “publish the result” (make it so that the user/another program sees the final file). If you mix these actions into one, you will get partial results that look “real”.
The strategy we will apply is very simple at the idea level:
- create a temporary file next to the target (.tmp/.part);
- write/copy only into it;
- if everything is successful—rename it to the target name;
- if something went wrong—try to delete the temporary file in finally (best-effort cleanup).
It is convenient to visualize it as a small flowchart:
flowchart TD
A[Need to obtain the target file] --> B[Create a temp file next to it: target.tmp/target.part]
B --> C[Write/copy data only into temp]
C --> D{Success?}
D -->|Yes| E[Rename temp -> target]
D -->|No / cancellation| F[Do not publish the result]
E --> G[Cleanup: delete temp leftovers if any]
F --> G
In Kotlin, the “guaranteed cleanup” discipline is usually built on try/finally. And the “guaranteed resource closing” discipline is built on .use { ... }, which automatically closes AutoCloseable even when exceptions happen. This is exactly the case where the language’s standard tools help you avoid writing “magic rituals” manually.
Why temp should be next to target
It is very tempting to make the temp file somewhere in /tmp, because “that’s where temporary stuff goes”. But we need predictability, not adventures. By placing temp next to target (in the same directory), you reduce the number of surprises related to permissions, different disks, and moves between file systems.
One more point is naming. .tmp or .part do two useful things: first, you can see with your own eyes “this is not final”; second, if another tool reads your folder (or even you, a week later), the chance of confusing it is lower. This is that rare case where a “nice name” is part of reliability.
Let’s make a small table so the brain does not argue with itself:
| Write approach | What the user sees during the process | “Half-file” risk | Clarity after a failure |
|---|---|---|---|
| Write directly to target.txt | target.txt appears and grows | high | “why does the file exist, but it’s corrupted?” |
| Write to target.txt.tmp, then rename | target.txt is absent until success | low | *.tmp remains; you can see the operation did not finish |
And yes, sometimes temp can also remain. But “report.txt.tmp remained” is a thousand times clearer than “report.txt exists, but it is broken”.
2. Cleanup and best-effort
Why cleanup is done in finally
In an ideal world, delete() always deletes the file, and renameTo() always renames it. In the real world, your file might be locked by the system, an antivirus, another program, or your own code (when you forgot to close a stream). Therefore cleanup must be best-effort: we honestly try, but we do not turn cleanup into a separate catastrophe that overrides the primary error.
The key point: finally runs on normal completion, on exceptions, and on coroutine cancellation (cancellation ultimately “arrives” as an exception too). So if you want to “clean up no matter what”, the place for that is almost always finally. In Kotlin, try { ... } finally { ... } is allowed even without catch, when your goal is to guarantee finishing the cleanup steps.
deleteQuietly(...)
Below is a small helper we will use in the examples. It is intentionally “quiet”: it does not crash if the delete fails.
import java.io.File
fun deleteQuietly(file: File) {
try {
if (file.exists()) file.delete()
} catch (_: Exception) {
// Cleanup best-effort: do not turn cleanup into a new error
}
}
There is a bit of self-irony here: we pretend delete is “simple”, and then add try/catch, because life likes to break our illusions.
3. Practice: safe writing and copying
writeTextSafely(...)
Now let’s assemble the first useful building block for our training application. Suppose we have a console utility that processes files and writes a report (log, summary, list of errors) to a text file. Writing the report directly to report.txt is dangerous: if we are cancelled or crash halfway through, we will leave a “stub report” that looks like the final result.
Let’s make a suspend function that writes to temp and then publishes the result via renameTo. Importantly, we perform file operations in Dispatchers.IO, because they are blocking.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
suspend fun writeTextSafely(target: File, text: String) {
val tmp = File(target.parentFile, target.name + ".tmp")
try {
withContext(Dispatchers.IO) {
tmp.parentFile?.mkdirs()
tmp.writeText(text)
}
val renamed = withContext(Dispatchers.IO) {
if (target.exists()) target.delete()
tmp.renameTo(target)
}
if (!renamed) error("Failed to rename ${tmp.name} to ${target.name}")
} finally {
deleteQuietly(tmp)
}
}
Note the meaning. While we are writing, target might not exist at all (or it stays old). Only when the temp write succeeds do we try to do the publish step (rename). And even if publish fails, we have temp, which we will try to clean up.
copySafely(...)
With text, things were relatively calm: writeText writes everything at once. But with large files you cannot do that (memory-wise, cancellation-wise, and control-wise). In the previous lecture, we already did chunked copying and added cooperative cancellation via isActive. Now we will add a second layer: do not write directly to the target file; write to .part, and only then publish.
Assume that the function copyCancellable(from, to) already exists from the previous lecture and copies the file in chunks, periodically checking for cancellation. Then the safe wrapper will look like this:
import java.io.File
suspend fun copySafely(from: File, target: File) {
val part = File(target.parentFile, target.name + ".part")
try {
part.parentFile?.mkdirs()
copyCancellable(from, part) // copy into a draft
val ok = if (target.exists()) target.delete() else true
if (!ok) error("Failed to delete the old file: ${target.name}")
val renamed = part.renameTo(target)
if (!renamed) error("Failed to publish the result: ${target.name}")
} finally {
deleteQuietly(part)
}
}
There is important “code psychology” here: we are not trying to make everything perfect at the file-system level (that is a whole separate science), but we are defining a clear, practical, and almost always sufficient contract for a training project: “either there is a new correct file, or there is no new file at all”. And .part along the way will either be deleted or remain as a signal that the operation did not finish.
Integrating into a console application: the report
Now let’s combine two ideas: we copy several files, and then we write the final report so that it does not appear partially. Within one lecture we are not building a huge framework—we just need a skeleton that demonstrates the style.
For the report, let’s introduce a simple result model. We are already familiar with data class, so we will use it as a “data container without extra philosophy”.
import java.io.File
data class CopyResult(
val from: File,
val to: File,
val ok: Boolean,
val message: String
)
Let’s build a string report. To avoid diving into large formatting topics, we will assemble plain text with line breaks.
fun buildReport(results: List<CopyResult>): String {
val lines = results.joinToString(separator = "\n") { r ->
val status = if (r.ok) "OK" else "ERROR"
"${status}: ${r.from.name} -> ${r.to.name} (${r.message})"
}
return lines + "\n"
}
And now a “mini-main” that shows the principle itself: we got results, assembled text, wrote the report via writeTextSafely. Here we are not re-implementing the whole concurrency pipeline; we are showing where exactly “safe result publication” is inserted.
import kotlinx.coroutines.runBlocking
import java.io.File
fun main() = runBlocking {
val results = listOf(
CopyResult(File("a.bin"), File("out/a.bin"), ok = true, message = "copied"),
CopyResult(File("b.bin"), File("out/b.bin"), ok = false, message = "not found")
)
val reportText = buildReport(results)
writeTextSafely(File("out/report.txt"), reportText)
println("Report saved") // Report saved
}
The semantic win: even if we are cancelled while writing the report or something crashes, we will not leave the user “half a report” disguised as the final document.
4. renameTo nuances
At this point, a beginner usually asks: “Why check renameTo at all, it… renames, right?” And here the most honest answer is: renameTo does not promise you happiness; it promises you a Boolean. If it returns false, it is not “weird”, it is the contract. That is why we turn false into an explicit error—to avoid a “silent failure” and a mysterious result.
There are several typical reasons why renaming can fail. Sometimes the target file already exists, and renaming does not replace it (which is why above we sometimes delete target in advance). Sometimes the file is still open by a stream (which is why .use {} is so important—it guarantees the resource is closed when the block finishes). Kotlin recommends the .use() idiom for closing AutoCloseable resources, so you do not keep streams open and do not break file operations.
Another practical nuance: if the temporary file is “somewhere else”, renaming can turn into a more complex OS-level operation. That is why we keep temp/part next to target: fewer surprises, more predictability.
And lastly: even if you did everything correctly, you can still end up in a situation where cleanup did not delete the .part (for example, the file is locked). This is unpleasant, but still better than leaving a corrupted “final” file. In our contract, an “extra .part” is garbage, while a “corrupted target” is a data error.
5. Typical mistakes when working with temp/part and cleanup
Mistake #1: writing directly to target and believing “it probably won’t be interrupted”.
When you write directly to the final file, you are essentially promising the world: “what is at this path is a finished result”. On cancellation or exception, the promise is broken, and then you get the nastiest category of bugs—“data looks valid, but actually isn’t”.
Mistake #2: cleanup in catch, but not in finally.
Coroutine cancellation and many unexpected failures can slip past your specific catch (or arrive as a different exception than you expected). If cleanup must happen “no matter what”, its place is finally, because it runs on any exit from the block.
Mistake #3: ignoring the renameTo result and pretending everything worked.
The most insidious variant: the operation was not published, but you did not check the Boolean and continued the program as if nothing happened. The user sees the old file or no file at all, and you are sure that “we wrote it”. Checking the result and turning false into an explicit error is not paranoia—it is adult life.
Mistake #4: the temp file is created not next to target.
If temp lives elsewhere, you increase the chance of issues with permissions, different devices/disks, and unpredictable renaming behavior. Next to target is a simple rule that sharply reduces the number of surprises.
Mistake #5: you forgot to close the stream and wonder why you cannot delete or rename the file.
Open InputStream/OutputStream and Reader/Writer can keep the file busy. That is why .use { ... } is not “nice style” but a practical necessity: it closes the resource even on exceptions, acting like a guaranteed completion discipline.
GO TO FULL VERSION