0

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.

4
  • Which ide do you use? Commented Apr 18, 2013 at 10:21
  • 4
    it is not a good idea to load the entire contents of a file into your memory. What purpose do you want to solve by loading everything into memory?Can u explain the use case Commented Apr 18, 2013 at 10:21
  • Either buy more memory, or, process your file line by line. Commented Apr 18, 2013 at 10:22
  • Please don't use StringBuffer when you can use StringBuilder. Commented Apr 18, 2013 at 11:14

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

The second option calling the java class with -Xmx has worked for me. Hope it won't cause any memory issues. Thanks for the input.
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.