Using a single StringBuilder - throws an OutofmemeoryException

execute the code below to read each line and concatenate based on 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, 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 mistake did I make?

Edit: I fixed at the suggestion of Bathsheba . 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 is the problem now?

+2
source share
1 answer

Use substringin a narrow loop is not recommended, as it will create many lines that may not be garbage collected to the end.

charAt char StringBuilder:

for (int j = 1; j <= 5; ++j){ /*ToDo - check the loop bounds*/
    sb.append(input.charAt(j)); /*StringBuilder has an overload for `char` insertion*/
}
+2

Source: https://habr.com/ru/post/1570138/


All Articles