CodeGym /Courses /Kotlin SELF /Directory traversal: walkTopDown, filters, and relative p...

Directory traversal: walkTopDown, filters, and relative paths

Kotlin SELF
Level 46, Lesson 1
Available

1. Introduction

When you hear “File Organizer”, you immediately want to write copyTo() and happily scatter files into folders like a cat scattering toys around the apartment. But bulk file operations are dangerous because they are irreversible (especially MOVE) and often break not where you expect: permissions, weird names, paths that are too long, files without extensions, nested directories, and so on.

So we need discipline: first we traverse the source directory and collect a list of “candidates”, then we filter it by rules (for example, by extensions), and only then we will build a plan and execute operations. Today is only the first piece of the pipeline: “tree → candidates”.

A small diagram of what we are building (for now, without executing operations):

flowchart TD
    A[Source directory sourceDir] --> B[walkTopDown: get all nodes of the tree]
    B --> C[filter: keep only files isFile]
    C --> D[extensionOrNull: extract extension]
    D --> E[filter: ext in allowedExt]
    E --> F[relativize: relative path inside sourceDir]
    F --> G[Candidate: candidate data for further processing]

2. Tree traversal: walkTopDown() and the isFile filter

File and Path: why we need both

In Kotlin/JVM, working with files often looks like “grab java.io.File and go”. And it’s true: File is convenient for quick checks like exists(), isFile, isDirectory, for walkTopDown(), and for simple operations. This style is common even in official examples for console scenarios.

But when it comes to paths as a structure rather than as strings, a second hero appears: java.nio.file.Path. Path has operations that are very important for us:

  • relativize(...) — build a relative path “inside the base directory”;
  • resolve(...) — join path parts without manual string concatenation and without guessing separators (/ vs \).

Today we critically need relativize(...). So we will live in a “hybrid world”: traversal is done via File, while we compute relative paths via Path. That’s normal: it’s not “two systems fighting”, it’s two convenient tools for different tasks.

Basic traversal: collect all files

When we say “traverse a directory”, we mean: walk through all nested folders and see every file that is inside. In Kotlin you can do this in different ways, but for our project the most practical and readable option is File.walkTopDown().

An important point: walkTopDown() returns a “walk over the tree” where you will encounter both directories and files. At this stage we don’t need directories as elements of the candidate list, so the first thing we do is keep only files.

Here is the minimal function to “collect all files at all”:

import java.io.File

fun collectAllFiles(sourceDir: File): List<File> {
    return sourceDir
        .walkTopDown()
        .filter { it.isFile }
        .toList()
}

Notice two nuances.

The first nuance is that walkTopDown() is not required to “download everything into memory immediately” — it traverses lazily, and toList() forces it to actually walk and collect the result. For beginners this is good news: you write it “like a pipeline”, and Kotlin performs the walk when you request the final result.

The second nuance: isFile cuts out directories, but it doesn’t solve every problem in the world: symlinks, special files, and access issues are not discussed today (and that’s fine). Our goal is a basic, robust prototype.

3. Extensions and filtering by allowedExt

File extension: carefully and predictably

Extracting an extension seems elementary: “take everything after the dot”. In practice, this is one of those tasks where beginners reliably step on rakes — and it’s not shameful; file names are not required to be “nice”.

Think about names like these:

  • photo.JPG — the extension exists, but the case is “shouting”;
  • archive.tar.gz — there are multiple dots; which extension is the “real” one?
  • .bashrc — there is a dot, but this is more like a “hidden name” than an extension;
  • no_extension — there is no dot;
  • weird. — there is a dot, but the extension is empty.

For File Organizer we need a stable, predictable function: if the extension is valid, return a lowercase string; if not, return null.

Here is a careful version:

import java.io.File

fun extensionOrNull(file: File): String? {
    val name = file.name
    val dot = name.lastIndexOf('.')

    if (dot <= 0) return null
    if (dot == name.lastIndex) return null

    return name.substring(dot + 1).lowercase()
}

Why dot <= 0?

  • dot == -1 means “there is no dot” — so there is no extension.
  • dot == 0 means “the dot is at the very beginning” (for example, .bashrc) — most utilities don’t treat this as an extension, and neither will we. Otherwise you would suddenly get the extension "bashrc", and then you’d be surprised why your “terminal config” ended up in the documents category.

Why dot == lastIndex?

  • Because weird. should not produce the extension "" (an empty string). An empty extension is a bad candidate; it’s easier to treat it as absent right away.

And what about archive.tar.gz?

  • Our code will return gz. This is not “the truth”; it’s a rule. For today’s project this is enough: we are building a prototype and we are not diving into detecting compound extensions (that’s a separate topic with separate policies).

Filtering by extensions: so .JPG doesn’t ruin your day

Now that we can extract an extension, what remains is simple: keep only those files whose extension is in the allowedExt set from the configuration.

But there is a typical trap here: you can’t compare “as is”. A user might enter JPG, .Jpg, jpg , while the file on disk might be Photo.JPEG. So we need normalization in a single style.

Assume that in the previous lecture you already wrote an extension normalizer:

fun normalizeExt(raw: String): String =
    raw.trim().removePrefix(".").lowercase()

Then the rule is: in configuration we store already-normalized extensions, and from the file we also extract a normalized one (we already do lowercase()), and comparison becomes “boring and reliable”.

Here is candidate collection with a filter:

import java.io.File

fun collectCandidates(sourceDir: File, allowedExt: Set<String>): List<File> {
    return sourceDir.walkTopDown()
        .filter { it.isFile }
        .filter { file ->
            val ext = extensionOrNull(file) ?: return@filter false
            ext in allowedExt
        }
        .toList()
}

Notice that we intentionally exclude files without an extension (null). This is not “the only correct way”; it’s a policy. If later you want to support files without extensions, you will implement it as a separate rule, not “accidentally because split happened to work that way”.

4. Relative paths and the candidate model

Relative path: why we need it

At this point beginners often have an honest question: “Why do we need a relative path if the file already has file.absolutePath?”

Imagine the source directory looks like this:

source/
  cats/
    cute.jpg
  docs/
    guide.pdf

If we store only the absolute path, we lose important information: where exactly inside source the file was located. And sometimes this is useful to preserve subfolder structure during placement.

For example, in the future we might want to get this:

target/
  images/
    cats/
      cute.jpg
  docs/
    docs/
      guide.pdf

To make that possible, we need to be able to say: “cute.jpg is located relative to source at cats/cute.jpg”. That is exactly what Path.relativize(...) gives us.

Minimal function:

import java.io.File
import java.nio.file.Path

fun relativePath(sourceDir: File, file: File): Path {
    return sourceDir.toPath().relativize(file.toPath())
}

But there is a tricky nuance: relativize works correctly when both paths are of the “same type” — either both absolute or both relative (and on the same file system). In real life, it’s better to normalize both paths to absolute.

A slightly more “bulletproof” version:

import java.io.File
import java.nio.file.Path

fun relativePath(sourceDir: File, file: File): Path {
    val src = sourceDir.toPath().toAbsolutePath().normalize()
    val f = file.toPath().toAbsolutePath().normalize()
    return src.relativize(f)
}

This is a bit longer, but you reduce the risk of weird effects if sourceDir was passed as . or ./source, while the file ended up in absolute form.

Candidate model: collect data “enough, but not too much”

At this point we already know how to:

  • walk the tree;
  • keep only files;
  • extract an extension;
  • filter by allowed extensions;
  • compute a relative path.

Now it’s important to take one more “architecture step”: don’t drag “raw File objects” throughout the project; instead, assemble a candidate model — a small data class that contains the fields we need.

Why is this important? Because later we will have multiple processing stages, and if in each place you recompute the extension and relative path, you’ll start duplicating code and getting inconsistent rules (which is favorite food for bugs).

Let’s create the model:

import java.io.File
import java.nio.file.Path

data class CandidateFile(
    val file: File,
    val ext: String,
    val relative: Path
)

There is not “everything in the world” here (for example, file size), because today we are collecting the minimum necessary for the next placement rules.

5. Collecting candidates from configuration

Now let’s put everything into a single function that accepts our configuration (from the previous lecture) and returns a list of candidates. Reminder of the idea: configuration is the utility’s contract, so it’s convenient when there is “one input”.

Assume we have:

data class OrganizerConfig(
    val sourceDir: String,
    val targetDir: String,
    val mode: Mode,
    val allowedExt: Set<String>,
    val conflictPolicy: ConflictPolicy,
    val dryRun: Boolean
)

Then the candidate collection function could look like this:

import java.io.File

fun collectCandidates(cfg: OrganizerConfig): List<CandidateFile> {
    val sourceDir = File(cfg.sourceDir)
    val srcPath = sourceDir.toPath().toAbsolutePath().normalize()

    return sourceDir.walkTopDown()
        .filter { it.isFile }
        .mapNotNull { file ->
            val ext = extensionOrNull(file) ?: return@mapNotNull null
            if (ext !in cfg.allowedExt) return@mapNotNull null

            val rel = srcPath.relativize(file.toPath().toAbsolutePath().normalize())
            CandidateFile(file = file, ext = ext, relative = rel)
        }
        .toList()
}

Notice the style: we use mapNotNull so that “files that don’t match” turn into null and are automatically dropped. This reads like: “convert a file into a candidate, and if you can’t — just skip it.”

And yes, this is the moment when many people first realize that Kotlin collections are not only for and if, but also a “transformation pipeline”. Don’t worry: if you still read mapNotNull slowly, that’s normal. In a couple of days you’ll read such chains much more easily.

Mini diagnostics: verify we didn’t collect “everything indiscriminately”

In practice, after writing the traversal, you want to make sure the function isn’t pulling in directories, for example, and that allowedExt really works. The simplest way is to temporarily print the first few candidates to the console.

Let’s add a small snippet to main (in a learning project, this is fine):

fun main() {
    val cfg = OrganizerConfig(
        sourceDir = "input",
        targetDir = "output",
        mode = Mode.COPY,
        allowedExt = setOf("jpg", "png", "pdf"),
        conflictPolicy = ConflictPolicy.SKIP,
        dryRun = true
    )

    val candidates = collectCandidates(cfg)
    println("Candidates: ${candidates.size}") // Candidates: 3 (example)

    for (c in candidates.take(3)) {
        println("${c.ext}: ${c.relative}")     // jpg: cats/cute.jpg (example)
    }
}

There are two useful effects here.

First, you immediately see that relative looks like “a path inside the source”, not like a full absolute path on your machine.

Second, you can quickly spot extension normalization mistakes. If you suddenly see JPG instead of jpg, it means you forgot lowercase().

6. Typical mistakes

Error #1: traversing the tree but forgetting filter { it.isFile }, and then “processing directories as files”.
This looks harmless until you try to extract an extension from a directory or “copy” a folder as a file. In the best case you’ll get strange results; in the worst case — exceptions and a half-broken run. The fix is simple: right after walkTopDown(), filter by isFile so the rest of your code works only with what it actually knows how to handle.

Error #2: extracting an extension via split(".") and getting unexpected values.
split creates many pieces, works poorly with names like archive.tar.gz, and also easily breaks on .bashrc or weird.. For a utility, predictability matters: it’s better to write a careful function once using lastIndexOf('.') and boundary checks than to later debug “why sometimes it’s null, sometimes an empty string, and sometimes it crashes”.

Error #3: comparing extensions without normalization and being surprised that photo.JPG doesn’t match jpg.
A file system is not obligated to help you be tidy. If you store jpg in allowedExt but extract JPG from the file, the comparison will honestly say “doesn’t match”. The conceptual fix: normalize both the configuration and the file extension to one format (usually lowercase() and “without the dot”).

Error #4: building a relative path via strings (substring) and running into separator and length bugs.
Manual string work on paths is like fixing a watch with a hammer: sometimes it works, but it’s scary to watch. Windows and Linux have different separators, paths can have different “prefixes”, and it’s easy to be off by one character. That’s why Path.relativize(...) exists: it does what you want, consistently across OSes.

Error #5: calling relativize on “different types of paths” (one relative, one absolute) and getting exceptions or weirdness.
This is a subtle point that few people guess on the first try. If sourceDir is set to "." but the file ends up absolute, then relativize may not behave as you expected. A habit that saves nerves: before relativize, convert both paths to toAbsolutePath().normalize() — then the comparison becomes stable and boring (and boredom in I/O is a compliment).

Error #6: mixing candidate collection with executing operations.
It’s very tempting to do copyTo right inside collectCandidates, “since we already found the file”. But that leads to code that is hard to test, hard to debug, and almost impossible to run safely in dry-run mode. Today’s principle is simple: traversal and candidate selection is a pure data preparation step. It changes nothing on disk; it only returns a list of structured candidates.

1
Task
Kotlin SELF, level 46, lesson 1
Locked
Directory reconnaissance
Directory reconnaissance
1
Task
Kotlin SELF, level 46, lesson 1
Locked
Extract the extension carefully
Extract the extension carefully
1
Task
Kotlin SELF, level 46, lesson 1
Locked
Candidate selection
Candidate selection
1
Task
Kotlin SELF, level 46, lesson 1
Locked
Candidate cards
Candidate cards
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION