How to create a read-only long buffer in java.


 

How to create a read-only long buffer in java.

In this tutorial, you will see how to create a read-only long buffer in java.

In this tutorial, you will see how to create a read-only long buffer in java.

How to create a read-only long buffer in java.

In this tutorial, we will see how to create a read-only long buffer that shares the content of another long buffer.

LongBuffer API :        

The java.nio.LongBuffer class extends java.nio.Buffer class. It provides the following methods:

Return type Method Description
static LongBuffer allocate( int capacity)  The allocate(..) method allocate a new long buffer.
abstract LongBuffer asReadOnlyBuffer() The asReadOnlyBuffer() method create a new read-only buffer that share the content of given long buffer.

Code

import java.nio.*;
import java.nio.LongBuffer;

public class ReadOnlyBuffer {
  public static void main(String[] args){
    LongBuffer longBuf = LongBuffer.allocate(256);
    longBuf.put(345678);
    longBuf.put(8765433);
    longBuf.flip();
    System.out.println("Content in long buffer.");
    while (longBuf.hasRemaining()) {
      System.out.println(longBuf.get());
    }
    System.out.println("Content in new long buffer.");
    longBuf.flip();
    LongBuffer newLBuffer = longBuf.asReadOnlyBuffer();
    for (int i = 0; i < newLBuffer.limit(); i++) {
      System.out.println(newLBuffer.get());
    }
    if (newLBuffer.isReadOnly()) {
      System.out.println("New buffer is read only");
    else {
      System.out.println("New buffer is not read only.");
    }
  }
}

Output

C:\>Java ReadOnlyBuffer
Content in long buffer.
345678
8765433
Content in new long buffer.
345678
8765433
New buffer is read only

Download this code

Ads