當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。