簡體   English   中英

為什么這需要這么長時間才能運行?

[英]Why does this take so long to run?

我是java的新手,我正在閱讀一個~25 MB的文件,並且需要永遠加載...有沒有其他選擇讓這更快? 是掃描儀無法處理大文件嗎?

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

您在每次迭代時都連接到文本,並且字符串在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()

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

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產生直到換行符的行,不包括它們。

在Java 7中,人們可以做到:

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

編碼明確給出,如UTF-8。 “Windows-1252”適用於Windows Latin-1等。

嘗試使用BufferedStreams ,例如BufferedInputStream, BufferedReader它們會加速它。 有關BufferedStreams更多信息,請看這里; http://docs.oracle.com/javase/tutorial/essential/io/buffers.html

而不是String使用StringBuilder因為StringJava是不可變的,它將在while循環的每次迭代中創建一個新的String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM