Java Reader close()方法及实例

Java Reader close()方法及实例

Java中Reader类的close()方法用于关闭流并释放在流中忙碌的资源,如果有的话。这个方法有以下结果。

  • 如果流是开放的,它将关闭流,释放资源。
  • 如果流已经被关闭,它将没有任何影响。
  • 如果在关闭后对流进行任何读取或其他类似的操作,它将引发IOException。

语法。

public abstract void close()

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

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

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

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

程序 1:

// Java program to demonstrate
// Reader close() 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);
            }
  
            // Close the stream using close()
            reader.close();
            System.out.println("Stream Closed.");
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出:

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

Integer value of character read: 101
Actual character read: e

Integer value of character read: 101
Actual character read: e

Integer value of character read: 107
Actual character read: k

Integer value of character read: 115
Actual character read: s
Stream Closed.

程序2。

// Java program to demonstrate
// Reader close() 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);
  
            // Close the stream using close()
            reader.close();
            System.out.println("Stream Closed.");
  
            // Check if the Reader is
            // ready to be read using ready()
            System.out.println("Is Reader ready "
                               + "to be read"
                               + reader.ready());
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出:

Stream Closed.
java.io.IOException: Stream closed

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程