English 中文(简体)
如何使用 Java 代码读取文件的所有行?
原标题:How to read all the lines of a file using java code?

我有一个奇怪的问题, 我有一个日志文件叫做交易Handler.log. 这是一个巨大的文件, 有17102条线。

wc -l transactionHandler.log
17102 transactionHandler.log

但当我运行以下的java代码 并打印行数 我得到2040 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);        
    }
}

你能告诉我原因吗?

最佳回答

From what I know, Scanner uses as delimiter by default. Maybe your file has . 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 ();
    }
}

根据"的文件,:

A line is considered to be terminated by any one of a line feed ( ), a carriage return ( ), or a carriage return followed immediately by a linefeed.

所以它非常适合有不同直线结束字符的文件。

试试看,看看它能做什么

问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签