Java FloatBuffer rewind()方法及示例
java.nio.FloatBuffer类的 rewind() 方法是用来倒退这个缓冲区的。该方法将位置设置为零,极限值不受影响,如果有任何先前标记的位置,将被丢弃。当有任何必要的通道写入或获取操作的序列时,应该调用这个方法。这意味着,如果缓冲区的数据已经被写入,那么它需要被复制到另一个数组中。比如说。
out.write(buf); // Writes the remaining data
buf.rewind(); // Rewind the buffer
buf.get(array); // Copy data into array
语法
public final FloatBuffer rewind()
参数: 该方法不接受任何参数。
返回值: 该方法返回这个缓冲区。
下面是说明rewind()方法的例子。
例子 1 :
// Java program to demonstrate
// rewind() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// defining and allocating FloatBuffer
// using allocate() method
FloatBuffer floatBuffer = FloatBuffer.allocate(4);
// put char value in FloatBuffer
// using put() method
floatBuffer.put(10.5f);
floatBuffer.put(20.5f);
// print the float buffer
System.out.println("Buffer before operation: "
+ Arrays.toString(
floatBuffer.array())
+ "\nPosition: "
+ floatBuffer.position()
+ "\nLimit: "
+ floatBuffer.limit());
// rewind the Buffer
// using rewind() method
floatBuffer.rewind();
// print the floatbuffer
System.out.println("\nBuffer after operation: "
+ Arrays.toString(
floatBuffer.array())
+ "\nPosition: "
+ floatBuffer.position()
+ "\nLimit: "
+ floatBuffer.limit());
}
}
输出。
Buffer before operation: [10.5, 20.5, 0.0, 0.0]
Position: 2
Limit: 4
Buffer after operation: [10.5, 20.5, 0.0, 0.0]
Position: 0
Limit: 4
例子 2 :
// Java program to demonstrate
// rewind() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// defining and allocating FloatBuffer
// using allocate() method
FloatBuffer floatBuffer
= FloatBuffer.allocate(5);
// put float value in floatBuffer
// using put() method
floatBuffer.put(10.5f);
floatBuffer.put(20.5f);
floatBuffer.put(30.5f);
// mark will be going to discarded by rewind()
floatBuffer.mark();
// print the buffer
System.out.println("Buffer before operation: "
+ Arrays.toString(
floatBuffer.array())
+ "\nPosition: "
+ floatBuffer.position()
+ "\nLimit: "
+ floatBuffer.limit());
// Rewind the Buffer
// using rewind() method
floatBuffer.rewind();
// print the buffer
System.out.println("\nBuffer after operation: "
+ Arrays.toString(
floatBuffer.array())
+ "\nPosition: "
+ floatBuffer.position()
+ "\nLimit: "
+ floatBuffer.limit());
}
}
输出。
Buffer before operation: [10.5, 20.5, 30.5, 0.0, 0.0]
Position: 3
Limit: 5
Buffer after operation: [10.5, 20.5, 30.5, 0.0, 0.0]
Position: 0
Limit: 5
参考资料: https://docs.oracle.com/javase/9/docs/api/java/nio/FloatBuffer.html#rewind-