为什么我要接受java.nio.BufferUnderflowException
我从下面的代码中获取BufferUnderflowException为什么我要接受java.nio.BufferUnderflowException,java,bytebuffer,bufferunderflowexception,Java,Bytebuffer,Bufferunderflowexception,我从下面的代码中获取BufferUnderflowException int length = mBuf.remaining(); char[] charBuff = new char[length]; for (int i = 0; i < length; ++i) { char[i] = mBuf.getChar(); } int length=mBuf.remaining(); char[]charBuff=新字符[长度]; 对于(int i=0;i
int length = mBuf.remaining();
char[] charBuff = new char[length];
for (int i = 0; i < length; ++i) {
char[i] = mBuf.getChar();
}
int length=mBuf.remaining();
char[]charBuff=新字符[长度];
对于(int i=0;i
mBuf是一个ByteBuffer。行“char[i]=mBuf.getChar();”崩溃
您对这个问题怎么看?您错误地认为一个字符的大小是一个字节。在Java中,字符是两个字节,因此
mBuf.getChar()
消耗两个字节。偶数表示该方法读取接下来的两个字节
如果使用返回的CharBuffer,则该缓冲区的剩余()方法将为您提供所需的数字
更新:根据您的评论,我现在了解到您的缓冲区实际上包含一个字节的字符。由于Java处理整个Unicode指令集(包含数十万个字符),因此您必须告诉它您使用的是哪个字符集(字符到字节编码):
// 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);
实际上,我用目标c在一个文件中写入字节序列。然后,我需要用java阅读这些内容。在obj c中,字符类型是一个字节。