I take BufferUnderflowException from following code.
int length = mBuf.remaining();
char[] charBuff = new char[length];
for (int i = 0; i < length; ++i) {
char[i] = mBuf.getChar();
}
mBuf is a ByteBuffer. Line "char[i] =mBuf.getChar();" is crashed.
What do you think about this problem?
You have mistakenly assumed that a char is one byte in size. In Java, a char is two bytes, so
mBuf.getChar()
consumes two bytes. The documentation even states that the method reads the next two bytes.If you use the CharBuffer returned by mBuf.asCharBuffer(), that buffer's remaining() method will give you the number you expect.
Update: Based on your comment, I understand now that your buffer does in fact contain one-byte characters. Since Java deals with the entire Unicode repertoire (which contains hundreds of thousands of characters), you must tell it which Charset (character-to-byte encoding) you are using: