Java Reader read(char[])方法及示例

Java Reader read(char[])方法及示例

Java中 Reader 类的 read(char[]) 方法是用来读取指定的字符到一个数组中。这个方法阻塞了流,直到。

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

语法

public int read(char[] charArray)

参数: 该方法接受一个强制性参数 charArray ,它是要写入流中的字符阵列。

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

异常: 如果在输入-输出时发生错误,该方法会抛出 IOException 。下面的方法说明了read(char[])方法的工作。

程序1 :

// 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& quot;
            ;
 
            // 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]

程序2

// 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]

计划3

// Use a BufferedReader to read characters from the console.
import java.io.*;
 
public class GFG {
 
    public static void main(String args[])
        throws IOException
    {
        char c;
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));
        System.out.println(
            "Enter the characters: , 'q' to quit.");
 
        // read characters
        do {
            c = (char)br.read();
            System.out.println(c);
        } while (c != 'q');
    }
}

输出

gfgisbest
g
f
g
i
s
b
e
s
t
q

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程