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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:38:54  来源:igfitidea点击:

ByteBuffer underflow

javabytebuffer

提问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

As described in java docs

如java文档中所述

Relative get method. ...

Throws: BufferUnderflowException If the buffer's current position is not smaller than its limit

相对获取方法。...

抛出: BufferUnderflowException 如果缓冲区的当前位置不小于其限制

Find more here

在这里找到更多

回答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 清空它