Scala Path.relativize
Compute a relative path between locations sharing a base.
A simple example
Path.relativize
- Start with Start at notes, target notes/a.txt
- Do this Find the relative route
- Result a.txt
Syntax
notes.relativize(image)
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonLink 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.
import java.nio.file.Files
import java.nio.file.Path
import scala.jdk.CollectionConverters._
object Lesson {
def main(args: Array[String]): Unit = {
val base = Files.createTempDirectory("lesson-")
try {
val image = base.resolve("images/map.png")
val steps = base.resolve("notes").relativize(image)
println(steps.iterator().asScala.mkString("/"))
} finally {
val tree = Files.walk(base)
try tree.sorted(java.util.Comparator.reverseOrder[Path]()).forEach(p => Files.delete(p))
finally tree.close()
}
}
}
../images/map.png
Go up one directory from notes, then enter images and select the diagram.
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.
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.
What to watch for
Both paths need compatible roots. The result depends on which directory is the starting point.