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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP