Pho*_*225 4 java file-io java.util.scanner
我有一个奇怪的问题,我有一个名为transactionHandler.log的日志文件.它是一个非常大的文件,有17102行.这是我在linux机器上执行以下操作时获得的:
wc -l transactionHandler.log
17102 transactionHandler.log
Run Code Online (Sandbox Code Playgroud)
但是,当我运行以下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);
}
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我原因吗?
据我所知,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 ();
}
}
Run Code Online (Sandbox Code Playgroud)
根据LineNumberReader的文档:
一条线被认为是由换行符('\n'),回车符('\ r')或回车符中的任何一个终止,后面紧跟换行符.
所以它非常适合具有不同行终止字符的文件.
试一试,看看它做了什么.