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

自古美人都是妖i 提交于 2019-12-10 16:09:26

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10715557/how-to-read-all-the-lines-of-a-file-using-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!