Search code examples
javaout-of-memorystringbuilderstreamreader

how to create a reader out of a bunch of Strings without appending them in a StringBuilder first?


Imagine I have several Stings containing large ammount of data. I must pass the concatenation of them to a method in a library I use. I can use either a String or a Reader for that.

  1. Appending them and passing an String is out of question as I might run into an OOM. There is no option to change -Xmx anymore.
  2. So, is there a way to create a reader based on ALL my strings without having to create a single string and then to create a StringReader? This way I could avoid the OOM

ps: I already set the initial capacity of the StringBuilder for my first option, but this is no enough, so I am looking for a way to implement 2.


Solution

  • You could implement a custom Reader whose data is drawn from a list of your Strings. Your concrete subclass would be required to implement only two methods: read(char[], int, int) and close(). When your reader finishes consuming one String, move on to the next.