0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Basic operation of NIO Buffer classes

Posted at

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());
	}

}

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?