ByteBuffer 的 get() 方法


在 java.nio.ByteBuffer 類的 get() 方法中可以讀取並增量緩衝區的當前位置的值。此方法將返回在當前緩衝區位置上的值。此外,如果出現下溢情況,將丟擲 BufferUnderflowException。

以下是展示此方法的程式:

示例

 線上演示

import java.nio.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      int n = 5;
      try {
         ByteBuffer buffer = ByteBuffer.allocate(n);
         buffer.put((byte)1);
         buffer.put((byte)2);
         buffer.put((byte)3);
         buffer.put((byte)4);
         buffer.put((byte)5);
         buffer.rewind();
         System.out.println("The ByteBuffer is: " + Arrays.toString(buffer.array()));
         byte val1 = buffer.get();
         System.out.println("
The value at current position of ByteBuffer is: " + val1); byte val2 = buffer.get(); System.out.println("The value at next position of ByteBuffer is: " + val2); } catch (IllegalArgumentException e) { System.out.println("Error!!! IllegalArgumentException"); } catch (ReadOnlyBufferException e) { System.out.println("Error!!! ReadOnlyBufferException"); } catch (BufferUnderflowException e) { System.out.println("Error!!! BufferUnderflowException"); } } }

輸出

The ByteBuffer is: [1, 2, 3, 4, 5]
The value at current position of ByteBuffer is: 1
The value at next position of ByteBuffer is: 2

更新時間:2019 年 7 月 30 日

401 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

入門
廣告
© . All rights reserved.