Java CharBuffer chars()方法及实例
java.nio.CharBuffer 类的 chars() 方法是用来返回一个int零扩展的char值流,从这个序列中。任何映射到代理代码点的char都会被不加解释地通过。当终端流操作开始时,流绑定到这个序列(具体来说,对于可变的序列,流的分割器是晚绑定的)。如果在该操作过程中序列被修改,那么结果是未定义的。
语法
public IntStream chars()
返回值: 该方法从该序列中返回一个 IntStream 的char值。下面是说明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 chars() 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 chars() 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-