Sunday 9 June 2019

When will you get ‘ReadOnlyBufferException’?


'ReadOnlyBufferException' thrown, when you try to insert data into a read only buffer.

package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

 public static void main(String args[]) throws Exception {
  /* Define new byte buffer of capacity 11 */
  ByteBuffer byteBuffer = ByteBuffer.allocate(26);

  /* Get the read-only buffer from byteBuffer */
  ByteBuffer readOnlyBuffer = byteBuffer.asReadOnlyBuffer();

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

 }
}

When you ran able application, you will endup in 'ReadOnlyBufferException'.

Exception in thread "main" java.nio.ReadOnlyBufferException
         at java.nio.HeapByteBufferR.put(Unknown Source)

         at com.sample.nio.Test.main(Test.java:14)

Previous                                                 Next                                                 Home

No comments:

Post a Comment