📜  Java中的 CharBuffer chars() 方法及示例

📅  最后修改于: 2022-05-13 01:54:55.103000             🧑  作者: Mango

Java中的 CharBuffer chars() 方法及示例

Java.nio.CharBuffer类的chars()方法用于返回一个 int 流,对该序列中的 char 值进行零扩展。任何映射到代理代码点的字符都会未经解释地传递。当终端流操作开始时,流绑定到这个序列(具体来说,对于可变序列,流的拆分器是后期绑定的)。如果在该操作期间修改了序列,则结果未定义。

句法:

public IntStream chars()

返回值:此方法从该序列中返回 char 值的IntStream

下面是说明 chars() 方法的示例:

示例 1:

// Java program to demonstrate
// chars() method
  
import java.nio.*;
import java.util.*;
import java.util.stream.IntStream;
  
public class GFG {
    public static void main(String[] args)
    {
        // creating object of CharBuffer
        // and allocating size capacity
        CharBuffer charbuffer
            = CharBuffer.allocate(3);
  
        // append the value in CharBuffer
        // using append() method
        charbuffer.append('a')
            .append('b')
            .append('c')
            .rewind();
  
        // print the CharBuffer
        System.out.println("Original CharBuffer:  "
                           + Arrays.toString(
                                 charbuffer.array())
                           + "\n");
  
        // Read char at particular Index
        // using charAt() method
        IntStream stream = charbuffer.chars();
  
        // Display the stream of int zero-extending
        // the char values from this sequence
        stream.forEach(System.out::println);
    }
}
输出:
Original CharBuffer:  [a, b, c]

97
98
99

示例 2:

// Java program to demonstrate
// chars() method
  
import java.nio.*;
import java.util.*;
import java.util.stream.IntStream;
  
public class GFG {
    public static void main(String[] args)
    {
        // creating object of CharBuffer
        // and allocating size capacity
        CharBuffer charbuffer
            = CharBuffer.allocate(5);
  
        // append the value in CharBuffer
        // using append() method
        charbuffer.append((char)140)
            .append((char)117)
            .append((char)118)
            .append((char)0)
            .append((char)90)
            .rewind();
  
        // print the CharBuffer
        System.out.println("Original CharBuffer:  "
                           + Arrays.toString(
                                 charbuffer.array())
                           + "\n");
  
        // Read char at particular Index
        // using charAt() method
        IntStream stream = charbuffer.chars();
  
        // Display the stream of int zero-extending
        // the char values from this sequence
        stream.forEach(System.out::println);
    }
}
输出:
Original CharBuffer:  [?, u, v,  , Z]

140
117
118
0
90

参考: https://docs.oracle.com/javase/9/docs/api/ Java/nio/CharBuffer.html#chars–