使用单个StringBuilder-抛出OutofmemeoryException [英] Using single StringBuilder - throws OutofmemeoryException
问题描述
像下面的代码一样,读取每一行并基于输入列表listValues进行串联.
do like the below code, to read each line and perform a concatenation based on an input list listValues.
BufferedReader br = null;
StringBuilder sb = new StringBuilder("");
InputStream in = new FileInputStream(new File(file));
br = new BufferedReader(new InputStreamReader(in), 102400);
for (String input; (input= br.readLine()) != null;) {
for (int i = 0; i < listValues.size(); i++) {
sb.append(input.substring(1, 5));
}
map.put(sb.toString(), someOtherValue);
sb.delete(0, sb.length());
}
通过设置每次都删除内容来对每次迭代使用相同的StringBuilder.仍会抛出
Using the same StringBuilder for each iteration by setting deleting the contents each time. Still throws
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.lang.String.substring(Unknown Source)
我犯了什么错误?
我已经按照 Bathsheba 的建议进行了更正. 但是现在抛出,
I have corrected as per Bathsheba's suggestion. But now throws,
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOfRange(Unknown Source)
at java.lang.String.<init>(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
在for (String input; (input= br.readLine()) != null;)
现在出什么问题了?
at for (String input; (input= br.readLine()) != null;)
What's the problem now?
推荐答案
在紧循环中使用substring
是不明智的,因为它会创建很多字符串,直到以后才可能被垃圾回收.
Using substring
within a tight loop is ill-advised since it will create many strings that may not be garbage collected until later.
您的解决方案是使用charAt
并将char
附加到StringBuilder
实例:
A solution in your case would be to use charAt
and append the char
s to the StringBuilder
instance:
for (int j = 1; j <= 5; ++j){ /*ToDo - check the loop bounds*/
sb.append(input.charAt(j)); /*StringBuilder has an overload for `char` insertion*/
}
这篇关于使用单个StringBuilder-抛出OutofmemeoryException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!