【问题标题】:count number of lines in file - Scala计算文件中的行数 - Scala
【发布时间】:2012-01-14 21:41:28
【问题描述】:

如何在 scala 的 unix 命令行上计算类似于 wc -l 的文本文件中的行数?

【问题讨论】:

    标签: parsing scala text


    【解决方案1】:
    io.Source.fromFile("file.txt").getLines.size
    

    请注意,getLines 返回 Iterator[String],因此您实际上并未将整个文件读入内存。

    【讨论】:

    • other question 的回答类似,这也会泄露文件描述符。
    【解决方案2】:

    来自another answer I posted的抄袭:

    def lineCount(f: java.io.File): Int = {
      val src = io.Source.fromFile(f)
      try {
        src.getLines.size
      } finally {
        src.close()
      }
    }
    

    或者,使用scala-arm

    import resource._
    
    def firstLine(f: java.io.File): Int = {
      managed(io.Source.fromFile(f)) acquireAndGet { src =>
        src.getLines.size
      }
    }
    

    【讨论】:

      【解决方案3】:
      val source = Source.fromFile(new File("file")).getLines
      var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }
      
      
      val source = Source.fromFile(new File("file")).getLines
      for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) }
      

      【讨论】:

        猜你喜欢
        • 2014-01-22
        • 2018-11-26
        • 2011-03-29
        • 2012-09-09
        • 2012-09-24
        • 2019-02-06
        • 2011-11-17
        • 2016-10-28
        相关资源
        最近更新 更多