@Validate
public static String
readUntil(@NotNull final InputStream stream, @NotNull final String terminator, @NotNull final Charset streamEncoding)
throws IOException
{
val result = new StringBuilder(256);
// this is the terminator string
val terminatorCharBuffer = CharBuffer.wrap(terminator.toCharArray());
// buffer holding the latest characters read
CharBuffer tempCharBuffer = CharBuffer.allocate(terminatorCharBuffer.length());
// read the first batch to fill the buffer
for (int i = 0; i < terminatorCharBuffer.length(); i++)
tempCharBuffer.put(readCharacter(stream, streamEncoding));
// compare and read next until arrays hold equal values
while (!(StringUtils.sequenceEqual(terminatorCharBuffer.array(), tempCharBuffer.array())))
{
// read next char
val ch = readCharacter(stream, streamEncoding);
// left shift elements in array, throw away the first read
tempCharBuffer = CharBuffer.wrap(tempCharBuffer.subSequence(1, tempCharBuffer.length())).append(ch);
// add to result string