有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

bytebuffer Java缓冲区标记并在for循环中重置

我见过生产代码,每次都在for循环中标记并放置初始化的缓冲区位置。有必要吗

 */
public static void writeToBuffer(final List<ByteBuffer> attachments, final ByteBuffer buffer) {
    for (ByteBuffer buf : attachments) {
        buf.mark();
        // copy content of buf to buffer
        buf.reset();
    }
}

共 (1) 个答案

  1. # 1 楼答案

    是的,这是必要的,如果您希望能够在代码后面的循环中开始读取缓冲区之前返回缓冲区位置

    示例:

    开始读取缓冲区之前的位置,这是设置标记的位置

    x-

    //读取缓冲区后,位置(可能)在末尾

    X

    //调用重置将移回标记位置,以便我们可以再次读取字节

    x-

    java doc开始:

    A buffer's mark is the index to which its position will be reset when the reset method is invoked. The mark is not always defined, but when it is defined it is never negative and is never greater than the position. If the mark is defined then it is discarded when the position or the limit is adjusted to a value smaller than the mark. If the mark is not defined then invoking the reset method causes an InvalidMarkException to be thrown.