用nio检查char行尾

时间:2018-03-22 13:59:25

标签: java iterator java-stream nio

我使用一些大文件。我需要检查文件以空行结尾或前一行以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结束,该怎么办?

由于

2 个答案:

答案 0 :(得分:0)

如果你找一个片段如何计算行数(即使是空行);这是:

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);

答案 1 :(得分:0)

你可以使用这个循环:

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