0

I work with some big file. I need to check that the file end with a empty line or the previous line end with a LF.

Exemple of file :

a
b
c
d
empty line

To read it I use nio and iterator.

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

When I check the count i I get 4 lines, but there is a 4 + 1 empty (so 5).

Any idea how to heck if the last line end with LF ?

Thanks

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Bosshoss
  • 783
  • 6
  • 24
  • 1
    Internally `Files.lines()` suppresses returning the linebreaks so you will never seen the EOF marker with the current code. Instead, you can take a look at using a more generic regex splitter and parsing the results yourself: https://stackoverflow.com/a/35327534/283788 – Ishan Chatterjee Mar 22 '18 at 14:04
  • Are you sure that there is an empty line at the end? E.g. Windows’ editor allows you to move the caret past the last line, but that doesn’t imply that there is an empty line stored in the file. When I try your code with a file that has an empty line, it *does* count the empty line. Likewise, just using `ligneFichier.count()` gives the correct answer too. – Holger Mar 23 '18 at 13:13

2 Answers2

0

If You look for a snippet how to count lines (even with empty lines); here it is:

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);
KarlR
  • 1,545
  • 12
  • 28
0

You could use this loop:

int numberOfLines = 0;
while (scanner.hasNextLine()) {
    numberOfLines++;
    scanner.nextLine();
}
Alex Blasco
  • 793
  • 11
  • 22