Library contents

Kotlin Path.relativeTo

Compute a relative path between locations sharing a base.

A simple example

Path.relativeTo

  1. Start with Start at notes, target notes/a.txt
  2. Do this Find the relative route
  3. Result a.txt
From inside notes, only the final filename is needed.

Syntax

Kotlin syntax
image.relativeTo(notes)
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Link a course handout to a diagram

A course will move between the teacher’s laptop and the school server. Compute a relative route from its notes folder to a sibling image folder so the handout can still find the same diagram.

Result../images/map.png
Lesson.kt
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.relativeTo
import kotlin.io.path.invariantSeparatorsPathString

fun main() {
    val base = Files.createTempDirectory("lesson-")
    try {
        val image = base.resolve("images/map.png")
        println(image.relativeTo(base.resolve("notes")).invariantSeparatorsPathString)
    } finally {
        base.toFile().deleteRecursively()
    }
}
Output
../images/map.png

Go up one directory from notes, then enter images and select the diagram.

Advertisements

Locate a rehearsal score

The choir stores each score inside a season folder. A catalogue starts in the parent directory. Which relative link reaches the file in the named subfolder? Use forward slashes in this example.

Givenspring / alto.txt
Worked resultspring/alto.txt

Locate a workshop handout

An instructor stores the current template in a class folder. A catalogue starts in the parent directory. Which relative link reaches the file in the named subfolder? Use forward slashes in this example.

Givenceramics / glaze.pdf
Worked resultceramics/glaze.pdf

What to watch for

Both paths need compatible roots. The result depends on which directory is the starting point.

Documentation for Path.relativeTo