Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a strange problem where I have a log file called transactionHandler.log.It is a very big file having 17102 lines.This i obtain when i do the following in the 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 the 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);        
    }
}

Can you please tell me the reason.

like image 652
Phoenix225 Avatar asked Feb 20 '23 09:02

Phoenix225


1 Answers

From what I know, Scanner uses \n as delimiter by default. Maybe your file has \r\n. You could modify 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 to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

so it's very adaptable for files that have different line terminating characters.

Give it a try, see what it does.

like image 84
Radu Murzea Avatar answered Feb 22 '23 22:02

Radu Murzea