【问题标题】:Check char end of line with nio用 nio 检查 char 行尾
【发布时间】:2018-09-01 00:08:29
【问题描述】:

我处理一些大文件。我需要检查文件是否以空行结尾或前一行以 LF 结尾。

文件示例:

a
b
c
d
empty line

为了阅读它,我使用 nio 和迭代器。

try (Stream<String> ligneFichier = Files.lines(myPath, myCharset)){
  Iterator<String> iterator = ligneFichier.iterator();
  int i = 0;
  while (iterator.hasNext()) {
    valeurLigne = iterator.next();
    i++;
  }
}

当我检查计数时,我得到 4 行,但有 4 + 1 为空(所以 5)。

知道最后一行是否以 LF 结尾吗?

谢谢

【问题讨论】:

  • 在内部 Files.lines() 禁止返回换行符,因此您将永远不会看到当前代码的 EOF 标记。相反,您可以看看使用更通用的正则表达式拆分器并自己解析结果:stackoverflow.com/a/35327534/283788
  • 你确定最后有一个空行吗?例如。 Windows 的编辑器允许您将插入符号移过最后一行,但这并不意味着文件中存储了一个空行。当我使用具有空行的文件尝试您的代码时,它 确实 计算空行。同样,仅使用ligneFichier.count() 也会给出正确答案。

标签: java iterator java-stream nio


【解决方案1】:

你可以使用这个循环:

int numberOfLines = 0;
while (scanner.hasNextLine()) {
    numberOfLines++;
    scanner.nextLine();
}

【讨论】:

    【解决方案2】:

    如果您寻找一个 sn-p 如何计算行数(即使是空行);在这里:

    int result = 0;
    try (
            FileReader input = new FileReader(filePath);
            LineNumberReader count = new LineNumberReader(input);
    ) { while (count.skip(Long.MAX_VALUE) > 0) {
            // Loop just in case the file is > Long.MAX_VALUE or skip() decides to not read the entire file
    }
    result = count.getLineNumber() + 1;                                    // +1 because line index starts at 0
    }
    System.out.println(result);
    

    【讨论】:

      猜你喜欢
      • 2012-08-26
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多