簡體   English   中英

用nio檢查char行的結尾

[英]Check char end of line with nio

我處理一些大文件。 我需要檢查文件以空行結尾還是前一行以LF結尾。

文件示例:

a
b
c
d
empty line

要閱讀它,我使用了nio和iterator。

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結尾怎么辦?

謝謝

如果您正在尋找一段代碼,如何計算行數(即使是空行); 這里是:

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

您可以使用以下循環:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM