Java Buffer isReadOnly()方法及示例
java.nio.Buffer 类的 isReadOnly() 方法是用来告诉这个缓冲区是否是只读的。
语法
public abstract boolean isReadOnly()
返回: 该方法将在且仅在该缓冲区为只读时返回true。
下面是说明 isReadOnly() 方法的例子。
例子 1 :
// Java program to demonstrate
// isReadOnly() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the capacity of the ByteBuffer
int capacity = 10;
// creating object of bytebuffer
// and allocating size capacity
ByteBuffer bb = ByteBuffer.allocate(capacity);
// putting the value in bytebuffer
bb.put((byte)10);
bb.put((byte)20);
bb.rewind();
// Typecast bytebuffer to Buffer
Buffer buffer = (Buffer)bb;
// checking buffer is backed by array or not
boolean isReadOnly = buffer.isReadOnly();
// checking if else condition
if (isReadOnly)
System.out.println("buffer is"
+ " ReadOnly buffer");
else
System.out.println("buffer is not"
+ " ReadOnly buffer");
}
}
输出:
buffer is not ReadOnly buffer
例子 2 :
// Java program to demonstrate
// isReadOnly() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the capacity of the ByteBuffer
int capacity = 10;
// creating object of bytebuffer
// and allocating size capacity
ByteBuffer bb = ByteBuffer.allocate(capacity);
// putting the value in bytebuffer
bb.put((byte)10);
bb.put((byte)20);
bb.rewind();
// Creating a read-only copy of ByteBuffer
// using asReadOnlyBuffer() method
ByteBuffer bb1 = bb.asReadOnlyBuffer();
// Typecast read-only ByteBuffer to read-only buffer
Buffer buffer = (Buffer)bb1;
// checking buffer is backed by array or not
boolean isReadOnly = buffer.isReadOnly();
// checking if else condition
if (isReadOnly)
System.out.println("buffer is"
+ " ReadOnly buffer");
else
System.out.println("buffer is not"
+ " ReadOnly buffer");
}
}
输出:
buffer is ReadOnly buffer
参考资料: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#isReadOnly-