3

I'm using an API that requires a Reader to read from, and this Reader should actually read from a (potentially very large) StringBuilder.

But using this:

new StringReader(stringBuilder.toString());

...will copy the internal StringBuilder's char array, which I want to avoid due to array size. Although, this char array is package-protected.

And no better luck with StringBuffer :(

Am I missing something?

Note: I can't use Java 7 at this time.

xav
  • 5,452
  • 7
  • 48
  • 57
  • 1
    You could make your own subclass that inherits from Reader (or StringReader); apparently it's pretty easy. – n3k0 Mar 03 '14 at 22:01
  • A `Reader` reads sequentially, a `StringBuilder/Buffer` can be changed randomly. How should this work without creating a `String`/copying the array in this system? If you only `append` to the `Builder/Buffer` you could construct a better producer than a `StringBuilder/Buffer` for the reader. – Hauke Ingmar Schmidt Mar 03 '14 at 22:02
  • @his: You're right. But in my case, I didn't have the choice on StringBuilder... I will try 'n3k0' or 'ChrisMartin' ideas for now. Thanks! – xav Mar 03 '14 at 22:11

1 Answers1

7

StringBuilder implements CharSequence, so you can use CharSequenceReader from Apache commons-io.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
  • [Guava now offers a `CharSequenceReader`, too](https://github.com/google/guava/blob/master/guava/src/com/google/common/io/CharSequenceReader.java) – sigpwned Jul 28 '18 at 22:39