DEV Community

Salad Lam
Salad Lam

Posted on

Basic operation of NIO Buffer classes

Notice

I wrote this article and was originally published on Qiita on 14 September 2021.


There are 4 internal indicators (capacity, limit, position, remaining) in Buffer classes, example below shows the change of these indicators.

import java.nio.Buffer;
import java.nio.ByteBuffer;

public class BufferTest {

    public static void main(String[] args) {
        ByteBuffer buf = ByteBuffer.allocate(8);
        System.out.println("[new buf]");
        printBufferInfo(buf);

        buf.put((byte) 1).put((byte) 2).put((byte) 3);
        System.out.println("[put 3 elements]");
        printBufferInfo(buf);

        for (int i = 0; i < buf.position(); i++)
            System.out.println(buf.get(i));
        System.out.println("[get 3 elements by index]");
        printBufferInfo(buf);

        buf.flip();
        System.out.println("[flip]");
        printBufferInfo(buf);

        for (int i = 0; i < 2; i++)
            System.out.println(buf.get());
        System.out.println("[get 2 elements]");
        printBufferInfo(buf);

        buf.compact();
        System.out.println("[compat]");
        printBufferInfo(buf);

        buf.put((byte) 4);
        System.out.println("[put 1 element]");
        printBufferInfo(buf);

        buf.clear();
        System.out.println("[clear]");
        printBufferInfo(buf);
    }

    public static void printBufferInfo(Buffer buf) {
        System.out.println("Capacity: " + buf.capacity());
        System.out.println("Limit: " + buf.limit());
        System.out.println("Position: " + buf.position());
        System.out.println("Remaining: " + buf.remaining());
    }

}
Enter fullscreen mode Exit fullscreen mode

The output is

[new buf]
Capacity: 8
Limit: 8
Position: 0
Remaining: 8
[put 3 elements]
Capacity: 8
Limit: 8
Position: 3
Remaining: 5
1
2
3
[get 3 elements by index]
Capacity: 8
Limit: 8
Position: 3
Remaining: 5
[flip]
Capacity: 8
Limit: 3
Position: 0
Remaining: 3
1
2
[get 2 elements]
Capacity: 8
Limit: 3
Position: 2
Remaining: 1
[compat]
Capacity: 8
Limit: 8
Position: 1
Remaining: 7
[put 1 element]
Capacity: 8
Limit: 8
Position: 2
Remaining: 6
[clear]
Capacity: 8
Limit: 8
Position: 0
Remaining: 8

Enter fullscreen mode Exit fullscreen mode

Top comments (0)