Class StringBuilderReader

  • All Implemented Interfaces:
    Closeable, AutoCloseable, Readable

    public class StringBuilderReader
    extends Reader
    Implements a Reader over a StringBuilder instance. Although one can use StringReader by passing it StringBuilder.toString(), it is better to use this class, as it doesn't mark the passed-in StringBuilder as shared (which will cause inner char[] allocations at the next append() attempt).
    Notes:
    • This implementation assumes the underlying StringBuilder is not changed during the use of this Reader implementation.
    • This implementation is thread-safe.
    • The implementation looks very much like StringReader (for the right reasons).
    • If one wants to reuse that instance, then the following needs to be done:
       StringBuilder sb = new StringBuilder("some text");
       Reader reader = new StringBuilderReader(sb);
       ... read from reader - don't close it ! ...
       sb.setLength(0);
       sb.append("some new text");
       reader.reset();
       ... read the new string from the reader ...