0

次のコードから BufferUnderflowException を取得します。

int length = mBuf.remaining();
char[] charBuff = new char[length];

for (int i = 0; i < length; ++i) {
   char[i] = mBuf.getChar();
}

mBuf は ByteBuffer です。行「char[i] =mBuf.getChar();」クラッシュしています。

この問題についてどう思いますか。

4

1 に答える 1

1

char のサイズが 1 バイトであると誤って想定しました。Java では、char は 2 バイトであるためmBuf.getChar()、2 バイトを消費します。ドキュメントには、メソッドが次の 2 バイトを読み取ることさえ記載されています。

mBuf.asCharBuffer()によって返された CharBuffer を使用すると、そのバッファのremaining() メソッドが期待する数を返します。

更新:あなたのコメントに基づいて、あなたのバッファーには実際に 1 バイト文字が含まれていることがわかりました。Java は Unicode レパートリー全体 (数十万文字を含む) を扱うため、使用している Charset (文字からバイトへのエンコーディング) を Java に伝える必要があります。

// 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);
于 2014-11-20T16:10:42.753 に答える