2013-08-06 405 views
3

我是java的新手,我正在閱讀一個大約25 MB的文件,並且需要永久加載...有沒有其他方法可以使這個更快?掃描儀是否無法處理大型文件?這爲什麼需要這麼長時間才能運行?

String text = ""; 
Scanner sc = new Scanner(new File("text.txt")); 
while(sc.hasNext()) { 
text += sc.next(); 
} 
+0

永遠有多久? – Thihara

+0

嘗試Apache Commons IO http://commons.apache.org/proper/commons-io/ – Abubakkar

+0

儘管我非常確定jvm會爲您優化它,但請嘗試使用['StrinbgBuilder'](http:// docs。 oracle.com/javase/7/docs/api/java/lang/StringBuilder.html)而不是字符串concat,並且只有在讀完文件並構建字符串後才創建字符串對象。 – amit

回答

7

您串聯到文本中每一次迭代,並且字符串是不變的每次迭代中創建一個新的String在Java中。這意味着每次text被「修改」時,它會在內存中創建一個新的String對象,從而導致大型文件的加載時間很長。當您持續更改String時,您應該嘗試使用並使用StringBuilder

你可以這樣做:

StringBuilder text = new StringBuilder(); 
Scanner sc = new Scanner(new File("text.txt"); 
while(sc.hasNext()) { 
    text.append(sc.next()); 
} 

當您要訪問文本的內容,你可以調用text.toString()

+1

+1但StringBuffer已過時。 – assylias

+0

這使得很多道理......我將String改爲StringBuilder,它創造了奇蹟!它從2分鐘加載時間到20秒!謝謝歌曲! – user2655552

+0

很高興爲你效勞。 @assylias我同意,自1.5以來BufferedString已經過時。編輯答案。 –

3

它是String +=,它每次創建一個不斷增長的新的String對象。 事實上,對於小於25 MB一個可以做(undermore):

StringBuilder sb = new StringBuilder(); 
BufferReader in = new BufferedReader(new InputStreamReader(
    new FileInputStream(new File("text.txt"), "UTF-8"))); 
for (;;) { 
    String line = in.readLine(); 
    if (line == null) 
     break; 
    sb.append(line).append("\n"); 
} 
in.close(); 
String text = sb.toString(); 

readLine產生高達換行符(S),這還不包括他們的線。

在Java 7中一個可以這樣做:

Path path = Paths.get("text.txt"); 
String text = new String(Files.readAllBytes(path), "UTF-8"); 

編碼都明確給出,爲UTF-8。 「Windows-1252」將用於Windows Latin-1等。

相關問題