Creates a read-only float buffer that shares the content of float buffer.


 

Creates a read-only float buffer that shares the content of float buffer.

In this tutorial you will see how to creates a read-only float buffer that shares the content of float buffer.

In this tutorial you will see how to creates a read-only float buffer that shares the content of float buffer.

Creates a read-only float buffer that shares the content of float buffer.

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

FloatBuffer API :

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

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

Code

import java.nio.*;
import java.nio.FloatBuffer;
public class ReadOnlyBuffer {
public static void main(String[] args){
FloatBuffer floatBuf = FloatBuffer.allocate(1024);
    floatBuf.put(12.061f);
    floatBuf.put(13.072f);
    floatBuf.flip();
System.out.println("Content in original buffer.");
    while (floatBuf.hasRemaining()) {
      System.out.println(floatBuf.get());
    }
FloatBuffer readBuffer = floatBuf.asReadOnlyBuffer();
     readBuffer.flip();
    System.out.println("Content in readOnlyBuffer.");
    while ( readBuffer.hasRemaining()) {
      System.out.println( readBuffer.get());
    }
    try {
       readBuffer.put(23.545f);
    catch (Exception e) {
  System.out.println("Buffer is read_only : " + e);
    }
  }
}

Output

C:\>java ReadOnlyBuffer
Content in original buffer.
12.061
13.072
Content in readOnlyBuffer.
12.061
13.072
Buffer is read_only : java.nio.ReadOnlyBufferException

Download this code

Ads