📌  相关文章
📜  Java中的 PushbackInputStream close() 方法及示例

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

Java中的 PushbackInputStream close() 方法及示例

Java中PushbackInputStream类的close()方法用于关闭输入流,并释放与该流相关联的系统资源。调用该方法后,如果该类再调用其他方法会抛出IOException。

句法:

public void close()
           throws IOException

指定者:该方法由AutoCloseable接口的close()方法和Closeable接口的close()方法指定。

覆盖:此方法覆盖FilterInputStream类的 close() 方法。

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

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

异常:如果发生 I/O 错误,此方法将引发IOException

下面的程序说明了 IO 包中 PushbackInputStream 类的 close() 方法:

方案一:

// Java program to illustrate
// PushbackInputStream close() method
  
import java.io.*;
  
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
        try {
  
            // Create an array
            byte[] byteArray
                = new byte[] { 'G', 'E', 'E',
                               'K', 'S' };
  
            // Create inputStream
            InputStream inputStr
                = new ByteArrayInputStream(byteArray);
  
            // Create object of
            // PushbackInputStream
            PushbackInputStream pushbackInputStr
                = new PushbackInputStream(inputStr);
  
            for (int i = 0; i < byteArray.length; i++) {
                // Read the character
                System.out.print(
                    (char)pushbackInputStr.read());
            }
  
            // Revoke close()
            pushbackInputStr.close();
        }
        catch (Exception e) {
            System.out.println("Stream is closed");
        }
    }
}
输出:
GEEKS

方案二:

// Java program to illustrate
// PushbackInputStream close() method
  
import java.io.*;
  
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
        try {
  
            // Create an array
            byte[] byteArray
                = new byte[] { 'G', 'E', 'E',
                               'K', 'S' };
  
            // Create inputStream
            InputStream inputStr
                = new ByteArrayInputStream(byteArray);
  
            // Create object of
            // PushbackInputStream
            PushbackInputStream pushbackInputStr
                = new PushbackInputStream(inputStr);
  
            // Revoke close()
            pushbackInputStr.close();
  
            for (int i = 0; i < byteArray.length; i++) {
                // Read the character
                System.out.print(
                    (char)pushbackInputStr.read());
            }
        }
        catch (Exception e) {
            System.out.println("Stream is closed");
        }
    }
}
输出:
Stream is closed

参考:
https://docs.oracle.com/javase/10/docs/api/java Java()