How to read all lines of a file using java code?

I have a strange problem when I have a log file called transactionHandler.log. This is a very large file with 17102 lines. This I get when I do the following in a linux machine:

wc -l transactionHandler.log 17102 transactionHandler.log 

But when I run the following java code and print the number of lines, I get 2040 as o / p.

 import java.io.*; import java.util.Scanner; import java.util.Vector; public class Reader { public static void main(String[] args) throws IOException { int counter = 0; String line = null; // Location of file to read File file = new File("transactionHandler.log"); try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { line = scanner.nextLine(); System.out.println(line); counter++; } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println(counter); } } 

Could you tell me the reason.

+4
source share
1 answer

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.

+8
source

Source: https://habr.com/ru/post/1413894/


All Articles