开发者

Split a filename into absolute paths in 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 a开发者_开发技巧n elegant, functional solution.


val path = "/what/an/awesome/path"
val file = new java.io.File(path)
val prefixes = Iterator.iterate(file)(_.getParentFile).takeWhile(_ != null).toList.reverse


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)


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.


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


Fancy-pants regex method:

val R = "(/.*)/".r
(path + '/').inits.collect{case R(x) => x}.toList
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜