我使用這是我從網上覆制以下基本函數讀取文本文件如何讓Java使用Scanner讀取非常大的文件?
public void read()
{
File file = new File("/Users/MAK/Desktop/data.txt");
System.out.println("Start");
try
{
//
// Create a new Scanner object which will read the data from the
// file passed in. To check if there are more line to read from it
// we check by calling the scanner.hasNextLine() method. We then
// read line one by one till all line is read.
//
Scanner scanner = new Scanner(file);
int lineCount = 0;
if (scanner == null)
{
System.out.println("Null File");
}
else
{
System.out.println(scanner.toString());
}
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.println("Line " + lineCount +" contain : " + line);
lineCount++;
}
System.out.println("End of Try Bluck");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
System.out.println("Exception Bluck");
}
System.out.println("End");
}
}
它的正常工作與中小尺寸文件(其中包含10 20萬餘行的數據) 然而它無法使用包含50萬行的文件。我沒有收到錯誤(至少沒有看到任何人)。那麼發生了什麼?我應該在這裏做些什麼來準備這麼大的文件?
注意:我已經在運行帶有4 GB RAM的Windows Server 2008的測試機器上增加了2 GB的堆。但這並沒有多大幫助!
請任何人都可以告訴我我應該在這裏做什麼?
更新01
以下是輸出
開始
java.util.Scanner中[定界符= \ p {javaWhitespace} +] [位置= 0 ] [[] = []] [[]] [[]] [[]] [[]] [ E] [正後綴=] [負後綴=] [NaN st環= \ Q \ E] [無窮大串= \Q∞\ E]的嘗試Bluck
末
你是最棒的! :) BufferedReader解決了這個問題! 謝謝!謝謝!謝謝!謝謝!謝謝!謝謝!謝謝!謝謝!謝謝!謝謝!謝謝! – 2010-02-11 09:01:52