在Nio中我们可以将ByteBuffer转换为只读buffer,用于传输时,客户端只能读取数据,不能修改内容。
import java.nio.ByteBuffer;
public class NioTest7 {
public static void main(String[] args) {
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
System.out.println(byteBuffer.getClass());
for (int i = 0; i < byteBuffer.capacity(); i++) {
byteBuffer.put((byte) i);
}
ByteBuffer readOnlyBuffer = byteBuffer.asReadOnlyBuffer();
System.out.println(readOnlyBuffer.getClass());
readOnlyBuffer.position(0);
readOnlyBuffer.put((byte) 0);
}
}
网友评论