List of usage examples for java.nio.charset CoderResult throwException
public void throwException() throws CharacterCodingException
From source file:com.google.flatbuffers.Table.java
/** * Create a Java `String` from UTF-8 data stored inside the FlatBuffer. * * This allocates a new string and converts to wide chars upon each access, * which is not very efficient. Instead, each FlatBuffer string also comes with an * accessor based on __vector_as_bytebuffer below, which is much more efficient, * assuming your Java program can handle UTF-8 data directly. * * @param offset An `int` index into the Table's ByteBuffer. * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`. *//*from w ww . j a va 2s. c o m*/ protected String __string(int offset) { CharsetDecoder decoder = UTF8_DECODER.get(); decoder.reset(); offset += bb.getInt(offset); ByteBuffer src = bb.duplicate().order(ByteOrder.LITTLE_ENDIAN); int length = src.getInt(offset); src.position(offset + SIZEOF_INT); src.limit(offset + SIZEOF_INT + length); int required = (int) ((float) length * decoder.maxCharsPerByte()); CharBuffer dst = CHAR_BUFFER.get(); if (dst == null || dst.capacity() < required) { dst = CharBuffer.allocate(required); CHAR_BUFFER.set(dst); } dst.clear(); try { CoderResult cr = decoder.decode(src, dst, true); if (!cr.isUnderflow()) { cr.throwException(); } } catch (CharacterCodingException x) { throw new Error(x); } return dst.flip().toString(); }
From source file:org.codehaus.groovy.grails.web.util.StreamByteBuffer.java
public String readAsString(Charset charset) throws CharacterCodingException { int unreadSize = totalBytesUnread(); if (unreadSize > 0) { CharsetDecoder decoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); CharBuffer charbuffer = CharBuffer.allocate(unreadSize); ByteBuffer buf = null;// w w w. j a va2 s . c o m while (prepareRead() != -1) { buf = currentReadChunk.readToNioBuffer(); boolean endOfInput = (prepareRead() == -1); CoderResult result = decoder.decode(buf, charbuffer, endOfInput); if (endOfInput) { if (!result.isUnderflow()) { result.throwException(); } } } CoderResult result = decoder.flush(charbuffer); if (buf.hasRemaining()) { throw new IllegalStateException("There's a bug here, buffer wasn't read fully."); } if (!result.isUnderflow()) { result.throwException(); } charbuffer.flip(); String str; if (charbuffer.hasArray()) { int len = charbuffer.remaining(); char[] ch = charbuffer.array(); if (len != ch.length) { ch = ArrayUtils.subarray(ch, 0, len); } str = StringCharArrayAccessor.createString(ch); } else { str = charbuffer.toString(); } return str; } return null; }