Sunday 9 June 2019

nio: Buffer: read only buffers


By calling the method 'asReadOnlyBuffer' on a Buffer instance, you can create a read-only buffer with the contents of the buffer that called 'asReadOnlyBuffer' method.

Ex
ByteBuffer readOnlyBuffer = byteBuffer.asReadOnlyBuffer();

Test.java
package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

 private static final String ALPHABETS = "abcdefghijklmnopqrstuvwxyz";

 private static void printStats(ByteBuffer byteBuffer) {
  int currentPosition = byteBuffer.position();
  int activeElePosition = byteBuffer.limit();
  System.out.println("position : " + currentPosition + ", limit : " + activeElePosition);
  System.out.println("\n");
 }

 public static void main(String args[]) throws Exception {
  /* Define new byte buffer of capacity 11 */
  ByteBuffer byteBuffer = ByteBuffer.allocate(26);
  System.out.println("Before inserting the data into buffer");
  printStats(byteBuffer);
  

  for (int i = 0; i < ALPHABETS.length(); i++) {
   byteBuffer.put((byte) ALPHABETS.charAt(i));
  }
  System.out.println("After inserting 26 characters into the buffer");
  printStats(byteBuffer);

  ByteBuffer readOnlyBuffer = byteBuffer.asReadOnlyBuffer();

  readOnlyBuffer.put(5, (byte) 67);

 }
}


Output
Before inserting the data into buffer
position : 0, limit : 26


After inserting 26 characters into the buffer
position : 26, limit : 26


Exception in thread "main" java.nio.ReadOnlyBufferException
 at java.nio.HeapByteBufferR.put(Unknown Source)
 at com.sample.nio.Test.main(Test.java:33)

Before inserting the data into buffer
position : 0, limit : 26


After inserting 26 characters into the buffer
position : 26, limit : 26


Exception in thread "main" java.nio.ReadOnlyBufferException
 at java.nio.HeapByteBufferR.put(Unknown Source)
 at com.sample.nio.Test.main(Test.java:33)

When you ran above application, you will end up in 'ReadOnlyBufferException'. To resolve the error remove below line.

readOnlyBuffer.put(5, (byte) 67);


Previous                                                 Next                                                 Home

No comments:

Post a Comment