* Preallocated CharBuffer for decoding bytes
*/
private CharBuffer cbuff = CharBuffer.wrap(carray);
public String readLine(Charset charset, byte delimiter) throws IOException {
CharsetDecoder decoder = charset.newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPLACE);
decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
int delim = delimiter&0xff;
int rc;
int offset = 0;
StringBuilder sb = null;
CoderResult res;
while ((rc = read())!=-1) {
if (rc == delim) {
break;
}
barray[offset++] = (byte)rc;
if (barray.length == offset) {
bbuff.position(0);
bbuff.limit(barray.length);
cbuff.position(0);
cbuff.limit(carray.length);
res = decoder.decode(bbuff, cbuff, false);
if (res.isError()) {
throw new IOException("Decoding error: " + res.toString());
}
offset = bbuff.remaining();
switch (offset) {
default:
System.arraycopy(barray, bbuff.position(), barray, 0, bbuff
.remaining());
break;
case 2:
barray[1] = barray[barray.length - 1];
barray[0] = barray[barray.length - 2];
break;
case 1:
barray[0] = barray[barray.length - 1];
break;
case 0:
}
if (sb == null) {
sb = new StringBuilder(cbuff.position());
}
sb.append(carray, 0, cbuff.position());
}
}
if (sb == null) {
if (rc == -1 && offset == 0) {
// We are at EOF with nothing read
return null;
}
sb = new StringBuilder();
}
bbuff.position(0);
bbuff.limit(offset);
cbuff.position(0);
cbuff.limit(carray.length);
res = decoder.decode(bbuff, cbuff, true);
if (res.isError()) {
System.out.println("Error");
}
sb.append(carray, 0, cbuff.position());
cbuff.position(0);
res = decoder.flush(cbuff);
if (res.isError()) {
System.out.println("Error");
}
sb.append(carray, 0, cbuff.position());
return sb.toString();