-1

I write a simple application on kotlin and I encountered the next problem:

I have relative (../../) and absolute (a/b/c) paths. I want to get path a/ . How to accomplish that without dancing with strings? Maybe there are methods in java/kotlin which allow to do it?

Nikolai
  • 19
  • 3

1 Answers1

4

I assume you target the JVM. Also, please note a/b/c is not an absolute path.

In Java we can process paths using the Path class. Merging two paths is performed by resolve() method and removing redundant parts like .. is called the "path normalization":

val base = Path.of("a/b/c")
val path = base.resolve("../../").normalize()
println(path) // prints: a
broot
  • 21,588
  • 3
  • 30
  • 35