【问题标题】:Counting lines of a file in Scala在 Scala 中计算文件的行数
【发布时间】:2014-01-22 22:45:00
【问题描述】:

我现在正在学习Scala,这是我的代码 sn-p 来计算文本文件中的行数。

  //returns line number of a file
  def getLineNumber(fileName: String): Integer = {
    val src = io.Source.fromFile(fileName)
    try {
      src.getLines.size     
    } catch {
      case error: FileNotFoundException => -1
      case error: Exception => -1
    }
    finally {
      src.close()
    }
  }

我正在使用 Programming in Scala book 中解释的 Source.fromFile 方法。这是问题所在:如果我的文本文件是这样的:

baris

ayse


deneme

我得到了正确的结果 6。如果我在单词 deneme 之后按回车键,我仍然得到数字 6,但是在这种情况下我期望 7。如果我在按回车后按空格,我会得到 7,这又是正确的。这是 Scala 标准库中的错误,还是更可能是我遗漏了什么?

最后,我的基本主要方法在这里如果有帮助:

  def main(args: Array[String]): Unit = {
    println(getLineNumber("C:\\Users\\baris\\Desktop\\bar.txt"))
  }

【问题讨论】:

  • 检查文本编辑器的设置。看起来不像是 Scala 做的。

标签: scala file-io newline standard-library


【解决方案1】:

如果您在单词 deneme 之后按回车键,只需将行尾序列(在您的情况下为 CR+LF)添加到第 6 行。您会看到光标转到新行,但您没有创建新行:您只需指定第六行结束。要创建新行,您必须在行尾序列之后放置一个字符,就像按空格时所做的那样。

【讨论】:

    【解决方案2】:

    它使用java.io.BufferedReaderreadLine。这是该方法的来源:

    /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
     * followed immediately by a linefeed.
     *
     * @return     A String containing the contents of the line, not including
     *             any line-termination characters, or null if the end of the
     *             stream has been reached
     *
     * @exception  IOException  If an I/O error occurs
     *
     * @see java.nio.file.Files#readAllLines
     */
    public String readLine() throws IOException {
        return readLine(false);
    }
    

    这叫:

    ...
    * @param      ignoreLF  If true, the next '\n' will be skipped
    ...
    String readLine(boolean ignoreLF) ...
    ...
    /* Skip a leftover '\n', if necessary */
                if (omitLF && (cb[nextChar] == '\n'))
                    nextChar++;
                skipLF = false;
                omitLF = false;
    

    所以基本上这就是它的实现方式。我想这取决于一条线对你意味着什么。您是否在计算包含某些内容或换行符的行? - 显然不同的东西。

    【讨论】:

    • 谢谢它与新行的解释有关。句子“一行被认为是由换行符 ('\n')、回车符 ('\r') 或回车符后紧跟换行符中的任何一个终止的。”在 javadoc 中解释了一切。
    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 2015-02-27
    • 2011-03-29
    • 2012-09-09
    • 2012-09-24
    • 2019-02-06
    • 2017-11-16
    相关资源
    最近更新 更多