CodeGym /Courses /Kotlin SELF /Absolute and relative paths

Absolute and relative paths

Kotlin SELF
Level 42, Lesson 0
Available

1. Introduction

When we say “read a file,” what we really mean is: “we need to explain to the operating system where exactly this file is located.” That’s what a path is for — a string (or an object) describing the address of a file/folder in the filesystem. In practice, a path often looks like "data/input.txt" or "C:\\Projects\\App\\data\\input.txt" — and that’s exactly where the adventures begin.

The problem is that the exact same path string can refer to different locations on disk depending on where the program is launched from. So the topic of paths isn’t pedantry — it’s a way to save yourself a couple hours of life and one nervous tic. Because the “file not found” error usually doesn’t mean the file is missing; it means the program is looking in the wrong place.

Absolute path

An absolute path is a path that fully describes a file’s location, starting from the filesystem “root.” It doesn’t depend on where you are or where you launched the program from. If the absolute path is correct, then the file either exists at that location or it doesn’t — no “magic” and no “well, it worked on my machine.”

On Windows, an absolute path usually starts with a drive letter (for example, C:\...), and on macOS/Linux — with /.... But the idea matters more: an absolute path is an address with country, street, building, and apartment, not “somewhere kind of near home.”

In Kotlin/JVM we often work with absolute paths via java.io.File, and one of the most useful diagnostic tricks is to look at absolutePath.

import java.io.File

fun main() {
    val f = File("data/input.txt")

    println("relative = ${f.path}")         // relative = data/input.txt
    println("absolute = ${f.absolutePath}") // absolute = .../data/input.txt
}

In this example, the file may not even exist — and that’s fine. File("...") here doesn’t “open a file”; it just stores the path and can show it in different forms.

Relative path

A relative path is a path that is not a full address; it’s computed “from somewhere.” And that “somewhere” is the key to the whole puzzle.

For example, the path "data/input.txt" means: “find the data folder in the process’s current working directory, and inside it the file input.txt.”

So a relative path is like the phrase “the store around the corner.” It works as long as we know which corner. But if you “teleport” to another neighborhood (launch the program differently), “around the corner” suddenly becomes a completely different corner.

Relative paths are very convenient because they make a project portable: you can keep data next to the project, commit the folder structure, and avoid hardcoding C:\Users\... into your code. But you have to use them correctly: always remember what the working directory is right now.

2. Working directory and file lookup

Working directory

The working directory is the folder relative to which relative paths are interpreted. And it’s one of the most common reasons why everything works in the IDE, but when you run from the terminal — “file not found,” or the other way around.

Checking “where we are right now” is as simple as it gets:

import java.io.File

fun main() {
    val wd = File(".").absolutePath
    println("Working dir = $wd") // Working dir = ... (absolute path of the current folder)
}

File(".") means “the current folder.” And absolutePath is a way to see what exactly the JVM considers the current working directory in this run.

Why is this so important? Because you can honestly write File("data/input.txt"), be sure the data folder exists, and the program will still say “not found” — if it was launched from a different directory and is looking for data somewhere other than where you expected.

Why the IDE and the terminal may behave differently

There’s a classic scenario.

You create a project with this structure:

MyApp/
  src/
  data/
    input.txt

You run it from the IDE — and the IDE may set the working directory to MyApp/. The relative path "data/input.txt" resolves to MyApp/data/input.txt — all good.

Then you run it differently: for example, from the terminal not from MyApp/, but from the parent folder or from some other directory entirely. Then "data/input.txt" resolves to other_folder/data/input.txt — and of course there is no file there.

The same logic applies not only to launching a program, but to any tools that read files via relative paths: relative paths are almost always interpreted from the process’s current working directory.

The takeaway is simple: a relative path is not “a path inside the project,” it’s “a path from the launch working directory.”

Diagnosing “file not found”

When you see FileNotFoundException or you just realize the program “can’t see the file,” a beginner’s first reaction is: “why can’t Kotlin find the file, it’s right there!” A slightly more experienced reaction is: “where is the program looking for the file?”

Here’s a golden mini-template for diagnostics:

import java.io.File

fun main() {
    val relative = "data/input.txt"
    val f = File(relative)

    println("Working dir = ${File(".").absolutePath}")
    println("Trying file = ${f.absolutePath}")
}

The point is that you get two important hints:

  • Working dir — the reference point for relative paths
  • Trying file — the absolute path the program is actually using

After that, the “magic” disappears: you literally see the address where the program is looking for the file. And then it turns out you expected .../MyApp/data/input.txt, but you got .../MyApp/src/data/input.txt or .../SomeOtherFolder/data/input.txt.

Mini diagram: how a relative path becomes an absolute one

Words are words, but it’s useful to see this once as a process. Roughly:

flowchart TD
    A["Relative path: data/input.txt"] --> B["Process working directory: WD"]
    B --> C["Combine: WD + data/input.txt"]
    C --> D["Absolute path: /.../WD/data/input.txt"]

This diagram doesn’t mean “simple string addition” at the OS level, but the meaning for us is exactly that: a relative path becomes absolute via the working directory.

3. File as a path object and building paths

File(path) is a path object

The word File is misleading: it seems like File("data/input.txt") “opens a file.” In reality, in Java/Kotlin, File is first and foremost a path object. It stores a path string and can:

  • return path (as you provided it),
  • return absolutePath (how the OS will see this path),
  • later — check existence, read, write, and so on.

So File is like an “Address” object, not like “the contents of a package.” You can create File("data/input.txt") even if the file doesn’t exist: it’s just “the address you want to use.”

How not to glue paths with strings

When a beginner first starts working with files, there’s a strong urge to do this:

val path = "data/" + "input.txt"

And that’s still relatively harmless. Then it turns into:

val path = "data" + "/" + "input.txt"

And then suddenly it’s Windows, backslashes, double slashes, spaces, and everything turns into an archaeological dig.

Even within this lecture (before Path.of(...), which comes later) you can do it much more neatly: build the path via File(parent, child). This isn’t a “magic” function; it’s just a safer way to join parts.

import java.io.File

fun main() {
    val dir = File("data")
    val file = File(dir, "input.txt")

    println(file.path)         // data/input.txt
    println(file.absolutePath) // .../data/input.txt
}

This reads as “file input.txt inside directory data,” not “a string assembled by shamanic rituals.”

4. Embedding paths into the app and making the output useful

“Where the project data lives”

To keep the examples concrete, let’s imagine our practical CLI app: say it’s a small expense tracker. Until now, it lived in memory, and now we want to store the data in the data/ folder.

Today we’re not reading or writing yet (that will be in the next lectures), but we can take an important step: centralize the place where the program “expects” the data file, and add diagnostics.

import java.io.File

private fun dataFile(): File {
    return File("data/expenses.txt")
}

fun main() {
    val f = dataFile()

    println("Working dir = ${File(".").absolutePath}")
    println("Data file (relative) = ${f.path}")         // Data file (relative) = data/expenses.txt
    println("Data file (absolute) = ${f.absolutePath}") // Data file (absolute) = .../data/expenses.txt
}

Here we did two good things at once.

First, the file path is now in one place, and later (when we start actually reading/writing) we won’t run into the situation “in one place it’s data/expenses.txt, in another it’s ./data/expenses.txt, and in a third it’s data\expenses.txt.”

Second, printing Working dir and the file’s absolute path is built-in diagnostics. At the moment you get “file not found,” you’ll already see where the program is looking.

Print the path so it can be checked manually

When you print paths, it’s useful to print them so a person can literally copy and paste, open them in Explorer/Terminal, and verify. That is, it’s better to print the absolute path and a short explanation next to it.

import java.io.File

fun main() {
    val reportFile = File("data/reports/today.txt")

    println("I will look for report at:")
    println(reportFile.absolutePath)
    // .../data/reports/today.txt
}

Yes, this looks too simple. But this is exactly the case where simplicity isn’t a sign of weakness; it’s a sign you don’t want to debug an “invisible” path.

5. Typical mistakes when working with paths

Mistake #1: assuming a relative path is resolved from the folder containing the code.
A very logical assumption, because in your head project = the folder with src. But the JVM doesn’t think that way. A relative path is resolved from the launch working directory, which depends on the IDE/terminal/Run Configuration settings. The best cure is to print File(".").absolutePath when you have issues.

Mistake #2: confusing “path inside the project” with “path at runtime.”
The data/ folder may sit next to src/, but if the working directory points to src/, then data/input.txt will be expected as src/data/input.txt. From the outside it looks like the path is “correct,” but it’s only correct in your head. The absolute path via absolutePath quickly brings you back to reality.

Mistake #3: gluing paths with strings and getting weird slashes.
String concatenation quickly leads to double separators, missing /, and “fixed it on Windows — broke it on Linux.” Even if you’re not using Path.of(...) yet, building a path via File(parent, child) already makes the code noticeably more reliable and readable.

Mistake #4: trying to diagnose file reading without diagnosing the path.
Beginners often immediately jump into try/catch, catch the exception, and print “read error.” But without printing the working directory and the absolute path, that message is nearly useless: you know it’s “not found,” but you don’t know “where it was searched.” The right order of thinking is: first figure out “where we’re looking,” then deal with reading.

Mistake #5: keeping the file path scattered throughout the project.
When the string "data/expenses.txt" appears in five places, one day you’ll change it in four and get a bug that feels like mysticism: “sometimes it reads the old, sometimes it writes to the new.” It’s much calmer when the path is created in one place (a function or constant) and then passed through the code as a File.

1
Task
Kotlin SELF, level 42, lesson 0
Locked
Path Navigator
Path Navigator
1
Task
Kotlin SELF, level 42, lesson 0
Locked
Path from the user
Path from the user
1
Task
Kotlin SELF, level 42, lesson 0
Locked
Address builder
Address builder
1
Task
Kotlin SELF, level 42, lesson 0
Locked
Bug report template
Bug report template
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION