How do I change the buffer mode between write and read?

A buffer can be read or written. To change the mode between the write mode and read mode we use the flip() method call on the buffer.

The are few things that you should know when you change between the write mode to the read mode. A buffer have the capacity, position and limit properties. The capacity will always be the same on write or read mode. But the position and limit will store different information in each mode.

In write mode the limit will be equals to the capacity, but in read mode the limit will be equals to the last position where the last data were written. The position on the write mode point where the data will be written in the buffer. When calling the flip() method the position will be set to 0 and the limit will be set to the last value of the position.

package org.kodejava.example.nio;

import java.nio.CharBuffer;

public class BufferFlip {
    public static void main(String[] args) {
        CharBuffer buffer = CharBuffer.allocate(1024);
        System.out.println("capacity = " + buffer.capacity());
        System.out.println("position = " + buffer.position());
        System.out.println("limit    = " + buffer.limit());

        buffer.put("Java NIO Programming");

        System.out.println("capacity = " + buffer.capacity());
        System.out.println("position = " + buffer.position());
        System.out.println("limit    = " + buffer.limit());

        buffer.flip();
        System.out.println("capacity = " + buffer.capacity());
        System.out.println("position = " + buffer.position());
        System.out.println("limit    = " + buffer.limit());
    }
}

The program will print the following result:

capacity = 1024
position = 0
limit    = 1024
capacity = 1024
position = 20
limit    = 1024
capacity = 1024
position = 0
limit    = 20
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply