Using single StringBuilder - throws OutofmemeoryException

孤者浪人 提交于 2019-12-11 03:20:00

问题


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());
}

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)

What is the mistake I have done?

Edit: 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)

at for (String input; (input= br.readLine()) != null;) What's the problem now?


回答1:


Using substring within a tight loop is ill-advised since it will create many strings that may not be garbage collected until later.

A solution in your case would be to use charAt and append the chars 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*/
}


来源:https://stackoverflow.com/questions/27522936/using-single-stringbuilder-throws-outofmemeoryexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!