2013-08-06 285 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等。

相关问题