📜  Java中的 PushbackReader close() 方法和示例

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

Java中的 PushbackReader close() 方法和示例

Java中PushbackReader类的close()方法用于关闭流并释放流中繁忙的资源(如果有)。该方法有以下结果:

  • 如果流是打开的,它会关闭释放资源的流
  • 如果流已经关闭,它将无效。
  • 如果对流执行任何读取或其他类似操作,则在关闭后,它会引发 IOException

句法:

public void close()

参数:此方法不接受任何参数

返回值:此方法不返回任何值。

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

下面的方法说明了 close() 方法的工作:

方案一:

// Java program to demonstrate
// PushbackReader close() method
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
            String s = "GeeksForGeeks";
  
            // Initializing a StringReader and PushbackReader
            StringReader stringReader
                = new StringReader(s);
            PushbackReader pushbackReader
                = new PushbackReader(stringReader);
  
            System.out.println("Is stream ready: "
                               + pushbackReader.ready());
  
            // Close the stream using close()
            pushbackReader.close();
            System.out.println("Stream Closed.");
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
Is stream ready: true
Stream Closed.

方案二:

// Java program to demonstrate
// PushbackReader close() method
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
            // Initializing a StringReader and PushbackReader
            String s = "GFG";
  
            StringReader stringReader
                = new StringReader(s);
            PushbackReader pushbackReader
                = new PushbackReader(stringReader);
  
            System.out.println("Is stream ready: "
                               + pushbackReader.ready());
  
            // Close the stream using close()
            pushbackReader.close();
            System.out.println("Stream Closed.");
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
Is stream ready: true
Stream Closed.

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