Java Reader read()方法及实例

来源:这里教程网 时间:2026-02-17 21:07:44 作者:

Java Reader read()方法及实例

Java中Reader类的read()方法用于从流中读取单个字符。这个方法阻断流,直到。

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

这个方法被声明为抽象的方法。这意味着Reader抽象类的子类应该覆盖这个方法,如果在读取一个字符时需要改变所需的操作。

语法。

public abstract int read()

参数。这个方法不接受任何参数

返回值。该方法返回一个整数值,即从流中读取的整数值。它的范围从0到65535。否则,如果没有读取任何字符,则返回-1。

异常。如果在输入输出时发生一些错误,该方法会抛出 IOException

下面的方法说明了read()方法的工作。

程序 1:

// Java program to demonstrate// Reader read() 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            // to be read from the stream            int ch;              // Read the first 5 characters            // to this reader using read() method            // This will put the str in the stream            // till it is read by the reader            for (int i = 0; i < 5; i++) {                ch = reader.read();                System.out.println("\nInteger value "                                   + "of character read: "                                   + ch);                System.out.println("Actual "                                   + "character read: "                                   + (char)ch);            }              reader.close();        }        catch (Exception e) {            System.out.println(e);        }    }}

输出:

Integer value of character read: 71Actual character read: GInteger value of character read: 101Actual character read: eInteger value of character read: 101Actual character read: eInteger value of character read: 107Actual character read: kInteger value of character read: 115Actual character read: s

程序2。

// Java program to demonstrate// Reader read() 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            // to be read from the stream            int ch;              // Read the first character            // to this reader using read() method            // This will put the str in the stream            // till it is read by the reader            ch = reader.read();            System.out.println("\nInteger value "                               + "of character read: "                               + ch);            System.out.println("Actual "                               + "character read: "                               + (char)ch);              reader.close();        }        catch (Exception e) {            System.out.println(e);        }    }}

输出:

Integer value of character read: 71Actual character read: G

参考资料: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#read-

相关推荐