我有一个奇怪的问题,我有一个名为 transactionHandler.log 的日志文件。这是一个非常大的文件,有 17102 行。这是我在 linux 机器上执行以下操作时获得的:
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);
}
}
能告诉我原因吗
最佳答案
据我所知,Scanner
默认使用 \n
作为分隔符。也许您的文件有 \r\n
。您可以通过调用 scanner.useDelimiter
来修改它,或者(这更好)尝试使用它作为替代方法:
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 ();
}
}
根据 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.
因此它非常适合具有不同行终止字符的文件。
试一试,看看效果如何。
关于java - 如何使用java代码读取文件的所有行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10715557/