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


Java CharArrayReader read(char[])用法及代碼示例


Java中CharArrayReader類的read(char [])方法用於將指定的字符讀取到數組中。此方法將流阻塞到:

  • 它已從流中獲取了一些輸入。
  • 發生了一些IOException
  • 閱讀時已到達流的末尾。

用法:

public int read(char[] charArray)

參數:此方法接受強製參數charArray,這是要在Stream中寫入的字符數組。


返回值:此方法返回一個整數值,該整數值是從流中讀取的字符數。如果未讀取任何字符,則返回-1。

異常:如果輸入輸出時發生某些錯誤,則此方法將引發IOException。

以下方法說明了read(char [])方法的用法方式:

程序1:

// Java program to demonstrate 
// CharArrayReader read(char[]) method 
  
import java.io.*; 
import java.util.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        try { 
  
            char[] str = { 'G', 'e', 'e', 'k', 's', 
                           'F', 'o', 'r', 
                           'G', 'e', 'e', 'k', 's' }; 
  
            // Create a CharArrayReader instance 
            CharArrayReader reader 
                = new CharArrayReader(str); 
  
            // Get the character array 
            // to be read from the stream 
            char[] charArray = new char[5]; 
  
            // Read the charArray 
            // to this reader using read() method 
            // This will put the str in the stream 
            // till it is read by the reader 
            reader.read(charArray); 
  
            // Print the read charArray 
            System.out.println( 
                Arrays 
                    .toString(charArray)); 
  
            reader.close(); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
輸出:
[G, e, e, k, s]

程序2:

// Java program to demonstrate 
// CharArrayReader read(char[]) method 
  
import java.io.*; 
import java.util.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        try { 
  
            char[] str = { 'G', 'e', 'e', 'k', 's', 
                           'F', 'o', 'r', 
                           'G', 'e', 'e', 'k', 's' }; 
  
            // Create a CharArrayReader instance 
            CharArrayReader reader 
                = new CharArrayReader(str); 
  
            // Get the character array 
            // to be read from the stream 
            char[] charArray 
                = new char[13]; 
  
            // Read the charArray 
            // to this reader using read() method 
            // This will put the str in the stream 
            // till it is read by the reader 
            reader.read(charArray); 
  
            // Print the read charArray 
            System.out.println( 
                Arrays 
                    .toString(charArray)); 
  
            reader.close(); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
輸出:
[G, e, e, k, s, F, o, r, G, e, e, k, s]

參考:



相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 CharArrayReader read(char[]) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。