Java 字节缓冲区下溢
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23678826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ByteBuffer underflow
提问by Crigges
I try to use the java libary ByteBuffer and wrote following code example:
我尝试使用 java libary ByteBuffer 并编写了以下代码示例:
ByteBuffer buf = ByteBuffer.allocate(32);
buf.putInt(4);
buf.putInt(8);
buf.putInt(12);
buf.putInt(16);
buf.putInt(20);
buf.putInt(24);
buf.putInt(28);
buf.putInt(32);
buf.order(ByteOrder.LITTLE_ENDIAN);
byte[] temp = new byte[32];
buf.get(temp);
For some reason it throws a BufferUnderflowExceptionin the last line.
出于某种原因,它在最后一行抛出了BufferUnderflowException。
I don't know why, can somebody explain me what I am doing wrong?
我不知道为什么,有人可以解释我做错了什么吗?
采纳答案by Roman Bondar
回答by mavarazy
Take a look at http://mindprod.com/jgloss/bytebuffer.html
看看http://mindprod.com/jgloss/bytebuffer.html
You must call ByteBuffer.flip to convert from filling the buffer via physical I/O to emptying it via ByteBuffer.get
您必须调用 ByteBuffer.flip 才能从通过物理 I/O 填充缓冲区转换为通过 ByteBuffer.get 清空它