当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java CharBuffer chars()用法及代码示例


java.nio.CharBuffer类的chars()方法用于从此序列返回int zero-extending 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-



相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 CharBuffer chars() methods in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。