Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a filename into absolute paths in Scala

Tags:

path

split

scala

Given the string

val path = "/what/an/awesome/path" 

how can I use Scala to create a list of absolute paths for each directory in path? The result should be:

List(/what, /what/an, /what/an/awesome, /what/an/awesome/path)

Bonus points for an elegant, functional solution.

like image 622
mre Avatar asked Oct 13 '11 12:10

mre


4 Answers

val path = "/what/an/awesome/path"
val file = new java.io.File(path)
val prefixes = Iterator.iterate(file)(_.getParentFile).takeWhile(_ != null).toList.reverse
like image 72
David Winslow Avatar answered Nov 05 '22 15:11

David Winslow


val path = "/what/an/awesome/path"

scala> path.tail.split("/").scanLeft(""){_ + "/" + _}.tail.toList
res1: List[java.lang.String] = List(/what, /what/an, /what/an/awesome, /what/an/awesome/path)
like image 29
Eastsun Avatar answered Nov 05 '22 15:11

Eastsun


Using Jesse Eichar's new Scala IO library (version 0.2.0) it looks like you can do something like this:

val path  = Path("/what/an/awesome/path")
val paths = (path :: path.parents).reverse

You might want to convert the Path objects in the resulting list to Strings but perhaps they would be safer and more useful left as Path objects.

This library, as far as I know, is being considered for inclusion in the Scala distribution.

like image 4
Don Mackenzie Avatar answered Nov 05 '22 15:11

Don Mackenzie


path.drop(1).split("/").foldLeft(List.empty[String])((list, string) => ((list.headOption.getOrElse("") + "/" + string) :: list)).reverse.toList

There's probably a cleaner way using scanLeft, but I wasn't able to figure it out

like image 2
Dave Griffith Avatar answered Nov 05 '22 15:11

Dave Griffith