ByteBuffer compact() 方法在 Java 中


緩衝區可以透過 java.nio.ByteBuffer 類中的 compact() 方法壓縮。此方法無需引數,並使用相同內容返回新的壓縮 ByteBuffer,並且如果是隻讀緩衝區,則會引發 ReadOnlyBufferException。

對此進行說明的程式如下 −

示例

 即時演示

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)5);
         buffer.put((byte)8);
         buffer.put((byte)3);
         System.out.println("The Original ByteBuffer is: " + Arrays.toString(buffer.array()));
         System.out.println("The position is: " + buffer.position());
         System.out.println("The limit is: " + buffer.limit());
         ByteBuffer bufferCompact = buffer.compact();
         System.out.println("
The Compacted ByteBuffer is: " + Arrays.toString(bufferCompact.array())); System.out.println("The position is: " + bufferCompact.position()); System.out.println("The limit is: " + bufferCompact.limit()); } catch (IllegalArgumentException e) { System.out.println("Error!!! IllegalArgumentException"); } catch (ReadOnlyBufferException e) { System.out.println("Error!!! ReadOnlyBufferException"); } } }

輸出

The Original ByteBuffer is: [5, 8, 3, 0, 0]
The position is: 3
The limit is: 5
The Compacted ByteBuffer is: [0, 0, 3, 0, 0]
The position is: 2
The limit is: 5

更新日期: 2019 年 7 月 30 日

199 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.