How do I write data into Buffer using put method?

The snippet below show you how to write some bytes into the ByteBuffer object through a call to the put() method.

package org.kodejava.example.nio;

import java.nio.ByteBuffer;

public class BufferPut {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.put((byte) 65);
        buffer.put((byte) 66);
        buffer.put((byte) 67);
        buffer.put((byte) 68);
        buffer.put((byte) 69);

        // Writes a sequence of bytes
        byte[] bytes = new byte[] {70, 71, 72, 73, 74};

        // Write to the beginning of the buffer
        buffer.put(0, (byte) 75);


        while (buffer.hasRemaining()) {
            System.out.print((char) buffer.get());

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply