java.nio.CharBuffer类的flip()方法用于翻转此缓冲区。将限制设置为当前位置,然后将该位置设置为零。如果定义了标记,则将其丢弃。在序列完成channel-read或放置操作之后,调用此方法为序列进行准备的channel-write或相对get操作。
例如:
buf.put(magic); // Prepend header
in.read(buf); // Read data into rest of buffer
buf.flip(); // Flip buffer
out.write(buf); // Write header + data to channel
当将数据从一个地方传输到另一个地方时,通常将此方法与compact()方法结合使用。
用法:
public final CharBuffer flip()
返回值:此方法返回此缓冲区。
下面是说明flip()方法的示例:
范例1:
// Java program to demonstrate
// flip() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declare and initialize the char array
char[] cb = { 'a', 'b', 'c' };
// wrap the char array into CharBuffer
// using wrap() method
CharBuffer charBuffe
r
= CharBuffer.wrap(cb);
// set position at index 1
charBuffer.position(1);
// print the char buffer
System.out.println("CharBuffer before flip:"
+ Arrays.toString(
charBuffer.array())
+ "\nPosition:"
+ charBuffer.position()
+ "\nLimit:"
+ charBuffer.limit());
// Flip the charBuffer
// using flip() method
charBuffer.flip();
// print the byte buffer
System.out.println("\nCharBuffer after flip:"
+ Arrays.toString(
charBuffer.array())
+ "\nPosition:"
+ charBuffer.position()
+ "\nLimit:"
+ charBuffer.limit());
}
}
输出:
CharBuffer before flip:[a, b, c] Position:1 Limit:3 CharBuffer after flip:[a, b, c] Position:0 Limit:1
范例2:
// Java program to demonstrate
// flip() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// defining and allocating CharBuffer
// using allocate() method
CharBuffer charBuffer
= CharBuffer.allocate(4);
// append char value in charBuffer
// using append() method
charBuffer.append('a');
charBuffer.append('b');
// print the char buffer
System.out.println("CharBuffer before flip:"
+ Arrays.toString(
charBuffer.array())
+ "\nPosition:"
+ charBuffer.position()
+ "\nLimit:"
+ charBuffer.limit());
// Flip the charBuffer
// using flip() method
charBuffer.flip();
// print the char buffer
System.out.println("CharBuffer before flip:"
+ Arrays.toString(
charBuffer.array())
+ "\nPosition:"
+ charBuffer.position()
+ "\nLimit:"
+ charBuffer.limit());
}
}
输出:
CharBuffer before flip:[a, b, c, ] Position:3 Limit:4 CharBuffer before flip:[a, b, c, ] Position:0 Limit:3
参考: https://docs.oracle.com/javase/9/docs/api/java/nio/CharBuffer.html#flip-
相关用法
- Java CharBuffer chars()用法及代码示例
- Java CharBuffer length()用法及代码示例
- Java CharBuffer read()用法及代码示例
- Java CharBuffer limit()用法及代码示例
- Java CharBuffer position()用法及代码示例
- Java CharBuffer clear()用法及代码示例
- Java CharBuffer charAt()用法及代码示例
- Java CharBuffer subSequence()用法及代码示例
- Java CharBuffer append()用法及代码示例
- Java CharBuffer rewind()用法及代码示例
- Java CharBuffer order()用法及代码示例
- Java CharBuffer reset()用法及代码示例
- Java CharBuffer mark()用法及代码示例
- Java DoubleBuffer flip()用法及代码示例
- Java FloatBuffer flip()用法及代码示例
注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 CharBuffer flip() methods in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。