Scala 读取文件

val lines = scala.io.Source.fromFile("file.txt").mkString

By the way, "scala." isn't really necessary, as it's always in scope anyway, and you can, of course, import io's contents, fully or partially, and avoid having to prepend "io." too.

The above leaves the file open, however. To avoid problems, you should close it like this:

val source = scala.io.Source.fromFile("file.txt")
val lines = try source.mkString finally source.close()

Another problem with the code above is that it is horrible slow due to its implementation nature. For larger files one should use:

source.getLines mkString "\n"

I had the same problem as Sharath Prabhal, and I got another (to me clearer) solution :

val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
s.groupBy(l => l).map(t => (t._1, t._2.length))
With as result :

Map(banana -> 1, oranges -> 3, apple -> 3)
shareedit

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,889评论 0 23
  • 欢迎进入课程! 首先请阅读《学习线路》,对全局有个了解,然后就开始吧。 应该指出,前两周可能枯燥一些,但是打好了基...
    胡巍阅读 410评论 0 4
  • 李野航阅读 196评论 0 0
  • 上路前 把心放好 纵然身在闹市 记得 一定要记得 让心远离尘嚣 把它放好 在鲜花盛开的地方 在清风吹过的地方 在溪...
    自我觉察日记本阅读 564评论 2 9

友情链接更多精彩内容