I\'m getting a java outOfMemoryError when I call this method - i\'m using it in a loop to parse many large files in sequence. my guess is that result.toString()
If your files to be processed are all very large, say more than a few hundred MB, then you really should go with stream processing instead of this "loading all into memory" way, just as @erickson suggested.
Otherwise, there are a few things you could try, all to reduce memory usage as much as possible:
StringBuffer an initial size same as the lenght of the given String buffer. This should reduce the unnecessary memory usage while expanding the StringBuffer in the process. I assume it is only replacing certain words of the original string and should be more or less the same in length.StringBuffer object instead. Calling its toString() only after you get rid of the original String object.