Java中的ByteBuffer asCharBuffer()方法
可以使用asCharBuffer()
类java.nio.ByteBuffer中的方法将ByteBuffer的视图创建为CharBuffer。此方法不需要任何参数,并且根据需要返回一个char缓冲区。该缓冲区反映了对原始缓冲区所做的更改,反之亦然。
演示此的程序如下所示-
示例
import java.nio.*; import java.util.*; public class Demo { public static void main(String[] args) { int n = 50; try { ByteBuffer bufferB = ByteBuffer.allocate(n); CharBuffer bufferC = bufferB.asCharBuffer(); bufferC.put('A'); bufferC.put('P'); bufferC.put('P'); bufferC.put('L'); bufferC.put('E'); bufferC.rewind(); char c; System.out.print("The CharBuffer is: "); while ((c = bufferC.get()) != 0) { System.out.print(c + " "); } } catch (IllegalArgumentException e) { System.out.println("Error!!! IllegalArgumentException"); } catch (ReadOnlyBufferException e) { System.out.println("Error!!! ReadOnlyBufferException"); } } }
输出结果
The CharBuffer is: A P P L E