📜  Java中的 Reader read(char[]) 方法和示例

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

Java中的 Reader read(char[]) 方法和示例

Java中Reader Class的read(char[])方法用于将指定的字符读入一个数组。此方法阻塞流直到:

  • 它从流中获取了一些输入。
  • 发生了一些 IOException
  • 它在读取时已到达流的末尾。

句法:

public int read(char[] charArray)

参数:此方法接受一个强制参数charArray ,它是要写入 Stream 的字符数组。

返回值:此方法返回一个整数值,它是从流中读取的字符数。如果没有读取任何字符,则返回 -1。

异常:如果输入输出时发生错误,此方法将抛出IOException

下面的方法说明了 read(char[]) 方法的工作:

方案一:

// Java program to demonstrate
// Reader read(char[]) method
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
  
            String str = "GeeksForGeeks";
  
            // Create a Reader instance
            Reader reader
                = new StringReader(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]

方案二:

// Java program to demonstrate
// Reader read(char[]) method
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
  
            String str = "GeeksForGeeks";
  
            // Create a Reader instance
            Reader reader
                = new StringReader(str);
  
            // Get the character array
            // to be read from the stream
            char[] charArray
                = new char[str.length()];
  
            // 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]

参考: https://docs.oracle.com/javase/9/docs/api/ Java/io/Reader.html#read–