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