Monday 10 June 2019

Nio: Set and get the buffer limit


By using the ‘limit’ method, you can set the buffer limit.

Test.java
package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

 public static void main(String args[]) throws Exception {
  ByteBuffer byteBuffer = ByteBuffer.allocate(10);

  System.out.println("Current limit of the buffer " + byteBuffer.limit());

  byteBuffer.limit(5);

  System.out.println("Current limit of the buffer " + byteBuffer.limit());
 }
}

Output
Current limit of the buffer 10
Current limit of the buffer 5

Even though capacity > limit, you can’t insert/get the elements > limit th position.


Test.java
package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

 public static void main(String args[]) throws Exception {
  ByteBuffer byteBuffer = ByteBuffer.allocate(10);

  System.out.println("Current limit of the buffer " + byteBuffer.limit());

  byteBuffer.limit(5);

  System.out.println("Current limit of the buffer " + byteBuffer.limit());
  
  byteBuffer.put(6, (byte) 'H');
  
 }
}

Output
Current limit of the buffer 10
Current limit of the buffer 5
Exception in thread "main" java.lang.IndexOutOfBoundsException
         at java.nio.Buffer.checkIndex(Unknown Source)
         at java.nio.HeapByteBuffer.put(Unknown Source)

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



Previous                                                 Next                                                 Home

No comments:

Post a Comment