Why do I take java.nio.BufferUnderflowException

2.2k views Asked by At

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?

1

There are 1 answers

1
VGR On BEST ANSWER

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:

// This is a pretty common one-byte charset.
Charset charset = StandardCharsets.ISO_8859_1;

// This is another common one-byte charset.  You must use the same charset
// that was used to write the bytes in your ObjectiveC program.
//Charset charset = Charset.forName("windows-1252");

CharBuffer c = charset.newDecoder().decode(mBuf);
char[] charBuff = new char[c.remaining()];
c.get(charBuff);