[英]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
因為String
在Java
是不可變的,它將在while
循環的每次迭代中創建一個新的String
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.