1. Introduction
When a utility works with files, it is always a little bit like a robot vacuum: the idea is great, but sometimes it finds a sock, decides it is trash, and drives off with it into the unknown. Bulk copy/move operations are an especially dangerous area: you process not one file but hundreds/thousands, and any error turns from “oops” into “oh no, where are my 10 years of photos?”.
In this lecture, we will add three things that greatly increase the chances that the user will remain your friend (and not the person who messages you at 3 a.m. saying “give me my files back”).
We will learn how to run the utility in dry-run mode (build a plan and “as if” execute it without changing the filesystem), write an operations log as simple lines to a file (so it is clear what happened), and generate a final report so that it is written atomically—that is, it does not leave a “half-file” on power loss, disk errors, or permission issues.
2. Dry-run: a rehearsal without filesystem changes
Dry-run sounds like “dry start,” but in essence it is a “rehearsal before the concert” mode. In it, the utility must go through all the intellectual steps: read the configuration, collect candidates, build a placement plan, check conflicts and… not perform real copyTo() and renameTo().
It is important to catch the philosophy: dry-run is not “we will do some part and skip the rest.” It must be completely free of filesystem changes. The maximum that is acceptable is writing a log and a report (and even then, logs/reports are usually written to a separate folder so they do not interfere with the target directory).
To make dry-run look in code like a “mode switch,” it is convenient to create a wrapper function that either calls the real execution or “simulates” results based on the plan.
Here is a minimal version—we will return a list of OpResult, but with the status “did not touch because dry-run”:
fun executeWithDryRun(plan: List<PlanItem>, cfg: OrganizerConfig): List<OpResult> {
if (!cfg.dryRun) return executePlan(plan, cfg)
return plan.map { item ->
OpResult(
source = item.source.path,
target = item.target.path,
status = Status.SKIPPED,
error = "dry-run"
)
}
}
Notice a small detail: we do not invent a new entity like “DryRunResult”; we use the existing OpResult. Yes, the SKIPPED status is not perfect philosophically, but it is practical: the report will show that the operations were not executed, and why.
If you want a more “honest” model, you can add a new PLANNED status, but that is already a change to the results contract. For today, we keep the model simple: status + explanation.
3. Operations journal: a log that saves your nervous system
A journal (log) is not the same as a report. A report is the outcome (how many files were processed, what errors occurred). A journal is “what happened along the way”: start, parameters, how many candidates were found, how many plans were built, where the report is located, and why we stopped (if we stopped).
A journal is especially useful in two cases: when the user says “it does not work,” and when you yourself open your code a week later and think “what did I mean?”. A programmer without logs is like a detective without a notebook: smart, maybe, but the evidence went somewhere else.
We will not build a “real” logging system with levels and rotation (that is a separate topic). We will make the simplest possible protocol: each line is one event. And we will add a simple timestamp to the line so it is clear in what order everything happened.
For time we will use the Java class LocalDateTime (it is available on the JVM, and that is exactly where we are right now).
import java.io.File
import java.time.LocalDateTime
fun appendLogLine(logFile: File, message: String) {
logFile.parentFile?.mkdirs()
val ts = LocalDateTime.now()
logFile.appendText("[$ts] $message\n")
}
Note: the function is small, but it does something important. It creates the directory for the log itself (if needed), adds a newline, and guarantees a consistent format.
Now in the “main scenario” you can write like this (still without a full main, just the idea):
import java.io.File
fun logStart(logFile: File, cfg: OrganizerConfig) {
appendLogLine(logFile, "Start File Organizer")
appendLogLine(logFile, "source=${cfg.sourceDir}, target=${cfg.targetDir}")
appendLogLine(logFile, "mode=${cfg.mode}, dryRun=${cfg.dryRun}")
}
It looks trivial, but in practice such a journal quickly stops being “extra” and becomes “thank you for having it.”
A small table so you do not mix up the roles (it really helps your brain):
| Artifact | For whom | When it is read | What is inside |
|---|---|---|---|
| Journal (log) | for the developer and diagnostics | when something went wrong | step-by-step events, parameters, hints |
| Report | for the user and the outcome | after execution | summary and list of operations |
| Console output | for “let me quickly check” | during the run | short messages, minimal details |
4. Report: first build the text, then write it
With reports, there are two typical beginner mistakes. The first is generating the text right in the middle of copying, mixing copyTo() and appendLine(...) into one mess. The second is writing the report directly to the final file and then being surprised: “why is the report cut off halfway?”
We will do it correctly: first build the report string (a pure function, without filesystem access), then write it separately (the I/O part).
A report usually consists of two parts: a short summary and a list of operations. For the summary, it is convenient to count how many results of each status there are. groupBy fits perfectly here, because it turns a list into groups by key. This is the same idea used in the standard library for grouping.
Minimal report rendering:
fun renderReport(cfg: OrganizerConfig, results: List<OpResult>): String {
val counts = results.groupBy { it.status }
.mapValues { (_, list) -> list.size }
val sb = StringBuilder()
sb.appendLine("File Organizer report")
sb.appendLine("mode=${cfg.mode}, dryRun=${cfg.dryRun}")
sb.appendLine("totals=$counts")
return sb.toString()
}
Already not bad, but we also want a list of operations. At the same time, it is important not to inflate the report to the size of a novel like “War and Peace: directories edition.” We will write one line per result and add the error only if it exists.
fun renderResultsList(results: List<OpResult>): String {
val sb = StringBuilder()
sb.appendLine()
sb.appendLine("Operations:")
for (r in results) {
val err = r.error?.let { " | error=$it" } ?: ""
sb.appendLine("${r.status}: ${r.source} -> ${r.target}$err")
}
return sb.toString()
}
Now you can assemble the full report by “concatenating strings”—that is fine, because we do this in memory, and it is not a massive operation of thousands of megabytes (and if it is—then you already know about StringBuilder and can do everything in a single sb):
fun renderFullReport(cfg: OrganizerConfig, results: List<OpResult>): String {
return renderReport(cfg, results) + renderResultsList(results)
}
5. Atomic report writing: temp file and renameTo
Atomic writing sounds like something from physics, but the everyday meaning is simple: “either the whole file is new, or the whole file is old; ‘half-written’ is not allowed.”
A broken report is not as scary as broken user files, but it is extremely unpleasant. Imagine: the utility processed 5000 files, 4999 are fine, and in the last second the report write fails. The user sees emptiness and thinks nothing happened at all. So the report is also part of reliability.
The scheme is:
flowchart TD
A[Formed report text in memory] --> B[Wrote to report.tmp]
B --> C{Write successful?}
C -- no --> D[Deleted tmp, returned false]
C -- yes --> E[Replaced old report.txt]
E --> F[Renamed tmp -> report.txt]
F --> G[Done: report is complete]
Implementation “in a teaching style” (simple but disciplined):
import java.io.File
import java.io.IOException
fun writeTextAtomically(target: File, text: String): Boolean {
val parent = target.parentFile ?: return false
if (!parent.exists() && !parent.mkdirs()) return false
val tmp = File(parent, target.name + ".tmp")
return try {
tmp.writeText(text)
if (target.exists() && !target.delete()) return false
tmp.renameTo(target)
} catch (e: IOException) {
false
} finally {
if (tmp.exists()) tmp.delete()
}
}
A couple of explanations, because it is easy to get lost here.
We create the directory for the report in advance. This matters more than it seems, because the report is often placed, for example, in targetDir/reports/report.txt, but the reports folder does not exist yet.
We write to .tmp. Even if the program crashes in the middle of writeText, it will only corrupt the temporary file, not the “main” report.
Before renameTo, we delete the old report if it existed. This is a “practical” approach, not the most ideal for all OSes, but within the course and a console utility it is enough.
In the finally block, we try to clean up tmp. Even if everything succeeded, tmp has already been renamed, exists() will be false, and we will not delete anything. If it failed—we at least try not to leave junk behind.
6. One unified scenario: dry-run, log, and report
Now we have all the “building blocks,” and all that remains is to assemble them into one clear run scenario. It is important to keep the style: “plan first, then execute, then report.”
Let us make a function runOrganizerOnce that takes a config, builds results, writes a log, and saves a report:
import java.io.File
fun runOrganizerOnce(cfg: OrganizerConfig, logFile: File, reportFile: File): Boolean {
appendLogLine(logFile, "Run started")
validateConfig(cfg)
val plan = buildPlan(cfg) // we assume you already have this function from previous lectures
appendLogLine(logFile, "Plan size=${plan.size}")
val results = executeWithDryRun(plan, cfg)
appendLogLine(logFile, "Results size=${results.size}")
val reportText = renderFullReport(cfg, results)
val ok = writeTextAtomically(reportFile, reportText)
appendLogLine(logFile, "Report written=$ok path=${reportFile.path}")
return ok
}
Here I intentionally use buildPlan(cfg) as “as if it already exists.” In your code, this will be a composition of previous steps: directory traversal, filtering, building PlanItem. The point is that in this lecture we do not go back into candidate collection and placement: we add a safety and reporting layer on top of an already working engine.
And this is where a nice architectural idea appears: if dry-run is just “a different execution branch,” then all the rest of the code stays the same. We are not building a second File Organizer “for rehearsal.” We have one organizer, just in different modes.
Dry-run and name conflicts
There is a subtle point that will definitely come up in a real project: “how should dry-run behave with name conflicts if there are already files in the target folder?”
The correct answer: dry-run must be able to report what will be done. That is, if ConflictPolicy.SKIP, in dry-run it makes sense to show that the file will be skipped because the target exists. If ConflictPolicy.BACKUP, it makes sense to show that a backup is planned. But you must not actually renameTo an existing file, because that is already a filesystem change.
Within our simplified approach (status SKIPPED + "dry-run"), we do not distinguish the reasons. That is fine for a learning step, but if you want a slightly more honest simulation, you can do an target.exists() check “inside dry-run” and write a more specific text into error without changing the filesystem:
fun simulateDryRun(item: PlanItem): OpResult {
val reason = if (item.target.exists()) "dry-run (target exists)" else "dry-run"
return OpResult(item.source.path, item.target.path, Status.SKIPPED, reason)
}
The key point: any exists() checks are safe. Any copyTo, renameTo, delete are forbidden in dry-run.
7. Common mistakes
Mistake #1: a dry-run that still “moves things a little.”
Sometimes dry-run is implemented like this: “well, we will only create folders via mkdirs(), that is not scary.” And this is where the slippery slope begins: today you create folders, tomorrow you delete the old report, the day after tomorrow you “accidentally” make a backup. In the end, the user runs dry-run and discovers changes. In a good design, dry-run does not change the filesystem at all; otherwise trust in the mode disappears.
Mistake #2: mixing execution and report generation into one huge loop.
Beginners often write it like: “copy the file → immediately write a line to the report,” and all of that in one for. This is inconvenient to debug and almost impossible to translate neatly into dry-run. It is much easier to keep discipline: execution returns List<OpResult>, the report is built by a separate function from the results, and writing the report is a third function.
Mistake #3: writing the report directly to the final file without a temp file.
It seems like “the report is small, what could happen to it.” But the report may be written to a network folder, the disk may be full, permissions may be restricted, and you end up with a truncated file. Temp + rename is a simple technique that sharply improves the quality of the utility: either the report is old or new, but not “halfway.”
Mistake #4: forgetting to create the directory for the log/report.
A very common situation: you nicely specify a path like target/reports/report.txt, but the reports folder does not exist. Then writeText fails, and you think the problem is in the copy code. A small parent.mkdirs() before writing saves tons of time on “why did it not write.”
Mistake #5: a log without time and context.
A log like “Start”, “Plan size=100”, “Done” is almost like no log at all. It has no time, no run parameters, no paths, no COPY/MOVE mode. Next time you see that file, you will not understand which run created it. Even a simple LocalDateTime.now() stamp and a couple of lines with the configuration turn a log from “noise” into “diagnostics.”
Mistake #6: hiding report write errors and always printing “success.”
Sometimes you want to make the “user experience” smooth and print println("Done!") even if writeTextAtomically returned false. That is a bad idea: the report is part of the result. If it did not get written, it is better to honestly tell the user in the console and write to the log that the report could not be saved (and where you tried to save it). Honesty here is not a moral category; it is a way to reduce the number of mysterious bug reports.
GO TO FULL VERSION