Java ByteBuffer limit()方法及实例
java.nio.ByteBuffer类的 limit() 方法是用来设置这个缓冲区的极限。如果位置大于新的极限,那么它就被设置为新的极限。如果标记被定义并且大于新的极限,那么它将被丢弃。
语法
public ByteBuffer limit(int newLimit)
返回值: 该方法返回这个缓冲区。
下面是说明limit()方法的例子。
例子 1 :
// Java program to demonstrate
// limit() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// defining and allocating ByteBuffer
// using allocate() method
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
// put byte value in byteBuffer
// using put() method
byteBuffer.put((byte)20);
byteBuffer.put((byte)30);
// print the byte buffer
System.out.println("ByteBuffer before compact: "
+ Arrays.toString(byteBuffer.array())
+ "\nPosition: " + byteBuffer.position()
+ "\nLimit: " + byteBuffer.limit());
// Limit the byteBuffer
// using limit() method
byteBuffer.limit(1);
// print the byte buffer
System.out.println("\nByteBuffer after compact: "
+ Arrays.toString(byteBuffer.array())
+ "\nPosition: " + byteBuffer.position()
+ "\nLimit: " + byteBuffer.limit());
}
}
输出
ByteBuffer before compact: [20, 30, 0, 0]
Position: 2
Limit: 4
ByteBuffer after compact: [20, 30, 0, 0]
Position: 1
Limit: 1
例子 2 :
// Java program to demonstrate
// limit() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// defining and allocating ByteBuffer
// using allocate() method
ByteBuffer byteBuffer = ByteBuffer.allocate(5);
// put byte value in byteBuffer
// using put() method
byteBuffer.put((byte)20);
byteBuffer.put((byte)30);
byteBuffer.put((byte)40);
// mark will be going to discarded by limit()
byteBuffer.mark();
// print the byte buffer
System.out.println("ByteBuffer before compact: "
+ Arrays.toString(byteBuffer.array())
+ "\nPosition: " + byteBuffer.position()
+ "\nLimit: " + byteBuffer.limit());
// Limit the byteBuffer
// using limit() method
byteBuffer.limit(4);
// print the byte buffer
System.out.println("\nByteBuffer after compact: "
+ Arrays.toString(byteBuffer.array())
+ "\nPosition: " + byteBuffer.position()
+ "\nLimit: " + byteBuffer.limit());
}
}
输出
ByteBuffer before compact: [20, 30, 40, 0, 0]
Position: 3
Limit: 5
ByteBuffer after compact: [20, 30, 40, 0, 0]
Position: 3
Limit: 4
参考资料: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#limit-int-
极客教程