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

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

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

Java中BufferedInputStream类的close()方法关闭输入流并释放与其关联的所有系统资源。一旦 close() 方法被调用,从任何输入文件读取被禁止并且系统将抛出一个 IOException。为了解决这个问题,用户可以使用 try-catch 块来捕获任何此类异常并抛出正确的指令。

句法:

public void close()

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

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

覆盖:该方法被类FilterInputStream中的close覆盖。

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

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

程序1:假设文件“c:/demo.txt”存在。

// Java program to illustrate
// BufferedInputStream.close() method
  
import java.io.*;
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
  
        // Create input stream 'demo.txt'
        // for reading containing
        // text "GEEKSFORGEEKS"
        FileInputStream inputStream
            = new FileInputStream("c:/demo.txt");
  
        // Convert inputStream to
        // bufferedInputStream
        BufferedInputStream buffInputStr
            = new BufferedInputStream(inputStream);
  
        // Get the number of bytes available
        // to read using available() method
        int rem_byte = buffInputStr.available();
  
        // Number of bytes available is printed
        System.out.println(
            "Remaining Byte: " + rem_byte);
  
        // Close the file
        buffInputStr.close();
    }
}
输出:
Remaining Byte: 13

程序2:假设文件“c:/demo.txt”存在。

// Java program to illustrate
// BufferedInputStream.close() method
  
import java.io.*;
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
        try {
  
            // create input stream 'demo.txt'
            // for reading containing
            // text "GEEKS"
            FileInputStream inputStream
                = new FileInputStream(
                    "c:/demo.txt");
  
            // convert inputStream to
            // bufferedInputStream
            BufferedInputStream buffInputStr
                = new BufferedInputStream(
                    inputStream);
  
            // get the number of bytes available
            // to read using available() method
            int rem_byte
                = buffInputStr.available();
  
            // number of bytes available is printed
            System.out.println(rem_byte);
  
            // close the file
            buffInputStr.close();
  
            // now throws io exception
            // if available() is invoked
            // after close()
            rem_byte = buffInputStr.available();
  
            System.out.println(rem_byte);
        }
        catch (IOException e) {
            // exception occurred.
            System.out.println(
                "Error: Sorry 'buffInputStr'"
                + " is closed");
        }
    }
}
输出:
5
Error: Sorry 'buffInputStr' is closed

参考资料: https: Java/io/BufferedInputStream.html#close()