[英]How to read all the lines of a file using java code?
我有一個奇怪的問題,我有一個名為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的文檔:
一條線被認為是由換行符('\\ n'),回車符('\\ r')或回車符中的任何一個終止,后面緊跟換行符。
所以它非常適合具有不同行終止字符的文件。
試一試,看看它做了什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.