在 Scala 中将文件名拆分为绝对路径

发布于 2024-12-09 19:04:01 字数 234 浏览 0 评论 0原文

给定字符串,

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

我如何使用 Scala 为路径中的每个目录创建绝对路径列表? 结果应该是:

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

优雅、实用的解决方案的加分。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

饭团 2024-12-16 19:04:01
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"
val file = new java.io.File(path)
val prefixes = Iterator.iterate(file)(_.getParentFile).takeWhile(_ != null).toList.reverse
太阳公公是暖光 2024-12-16 19:04:01
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)
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)
记忆で 2024-12-16 19:04:01

使用 Jesse Eichar 的新 Scala IO 库 (版本 0.2.0)看起来您可以执行以下操作:

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

您可能希望将结果列表中的 Path 对象转换为字符串,但也许将它们保留为 Path 对象会更安全、更有用。

据我所知,该库正在考虑包含在 Scala 发行版中。

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.

幽梦紫曦~ 2024-12-16 19:04:01
path.drop(1).split("/").foldLeft(List.empty[String])((list, string) => ((list.headOption.getOrElse("") + "/" + string) :: list)).reverse.toList

使用 scanLeft 可能有一种更干净的方法,但我无法弄清楚

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

§普罗旺斯的薰衣草 2024-12-16 19:04:01

花式裤子正则表达式方法:

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

Fancy-pants regex method:

val R = "(/.*)/".r
(path + '/').inits.collect{case R(x) => x}.toList
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文