From what I know, Scanner
by default uses \n
as a delimiter. Perhaps your file has \r\n
. You can change this by calling scanner.useDelimiter
or (and this is much better) try using this as an alternative:
import java.io.*; public class IOUtilities { public static int getLineCount (String filename) throws FileNotFoundException, IOException { LineNumberReader lnr = new LineNumberReader (new FileReader (filename)); while ((lnr.readLine ()) != null) {} return lnr.getLineNumber (); } }
According to the documentation of LineNumberReader :
A line is considered terminated by any of the lines ('\ n'), carriage return ('\ r'), or subsequent carriage return immediately by line feed.
therefore, it is very adaptable for files with different line endings.
Try it, see what he does.
source share