Navin
Navin

Reputation: 299

String buffer - OutOfMemoryError

I am having string buffer variable which holds the input i read from a file. Some cases i am getting input file in huge size. In those cases i am getting the OutOfMemoryError.

Here is my code:

StringBuffer response = new StringBuffer("");
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
        response.append(inputLine);
in.close();

Kindly help me how to resolve this issue.

Upvotes: 0

Views: 562

Answers (3)

OldCurmudgeon
OldCurmudgeon

Reputation: 65851

A further alternative would be to only hold an index of the file in memory. It depends what you want to do with it.

If, for example, you wish to display the file contents on screen, you could open the file for random access and scan through it, recording the offset of the beginning of each line in the file. You could then access each line individually by looking up the line in your index, seeking to the indicated location and reading from there.

Upvotes: 0

Greg Haskins
Greg Haskins

Reputation: 6794

If the file you are processing is huge, you may need to find a way to do that processing on the fly instead of reading the whole file into a StringBuffer in memory. Depending on how the data is structured, this might be performing some action for each line read in, or every several lines.

Upvotes: 1

Amir Kost
Amir Kost

Reputation: 2168

Either read the input in chunks, or change the -Xmx parameter (maximum memory size) in your JVM to a larger size.

Upvotes: 1

Related Questions