Java ByteBuffer asReadOnlyBuffer()方法及示例
java.nio.ByteBuffer 类的 asReadOnlyBuffer() 方法用于创建一个新的、只读的字节缓冲区,共享这个缓冲区的内容。
新的缓冲区的内容将是这个缓冲区的内容。对这个缓冲区内容的修改将在新的缓冲区中可见;然而,新的缓冲区本身将是只读的,不允许修改共享的内容。两个缓冲区的位置、极限和标记值将是独立的。
新缓冲区的容量、极限、位置和标记值将与这个缓冲区的相同。
如果这个缓冲区本身是只读的,那么这个方法的行为与复制方法完全相同。
语法:
public abstract ByteBuffer asReadOnlyBuffer()
返回值: 该方法返回新的只读字节缓冲区,其内容与该缓冲区的内容相同。
下面是说明asReadOnlyBuffer()方法的例子。
例子 1 :
// Java program to demonstrate
// asReadOnlyBuffer() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the capacity of the ByteBuffer
int capacity = 4;
// Creating the ByteBuffer
try {
// creating object of ByteBuffer
// and allocating size capacity
ByteBuffer bb = ByteBuffer.allocate(capacity);
// putting the int to byte typecast value in ByteBuffer
bb.put((byte)20);
bb.put((byte)30);
bb.put((byte)40);
bb.put((byte)50);
bb.rewind();
// print the ByteBuffer
System.out.println("Original ByteBuffer: "
+ Arrays.toString(bb.array()));
// Creating a read-only copy of ByteBuffer
// using asReadOnlyBuffer() method
ByteBuffer bb1 = bb.asReadOnlyBuffer();
// print the ByteBuffer
System.out.print("\nReadOnlyBuffer ByteBuffer: ");
while (bb1.hasRemaining())
System.out.print(bb1.get() + ", ");
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出。
Original ByteBuffer: [20, 30, 40, 50]
ReadOnlyBuffer ByteBuffer: 20, 30, 40, 50,
例子 2 :
// Java program to demonstrate
// asReadOnlyBuffer() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the capacity of the ByteBuffer
int capacity = 4;
// Creating the ByteBuffer
try {
// creating object of ByteBuffer
// and allocating size capacity
ByteBuffer bb = ByteBuffer.allocate(capacity);
// putting the int to byte typecast value in ByteBuffer
bb.put((byte)20);
bb.put((byte)30);
bb.put((byte)40);
bb.put((byte)50);
bb.rewind();
// print the ByteBuffer
System.out.println("Original ByteBuffer: "
+ Arrays.toString(bb.array()));
// Creating a read-only copy of ByteBuffer
// using asReadOnlyBuffer() method
ByteBuffer bb1 = bb.asReadOnlyBuffer();
// print the ByteBuffer
System.out.print("\nReadOnlyBuffer ByteBuffer: ");
while (bb1.hasRemaining())
System.out.print(bb1.get() + ", ");
// try to change read only bytebuffer
System.out.println("\n\nTrying to get the array"
+ " from bb1 for editing");
byte[] bbarr = bb1.array();
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出。
Original ByteBuffer: [20, 30, 40, 50]
ReadOnlyBuffer ByteBuffer: 20, 30, 40, 50,
Trying to get the array from bb1 for editing
Exception thrown : java.nio.ReadOnlyBufferException
极客教程