📜  Java中的 FileInputStream close() 方法及示例

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

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

FileInputStream 类有助于以字节序列的形式从文件中读取数据。 FileInputStream 用于读取原始字节流,例如图像数据。要读取字符流,请考虑使用 FileReader。

FileInputStream.close() 方法

对文件进行任何操作后,我们必须关闭该文件。为此,我们有一个 close 方法。我们将在本文中了解到这一点。 FileInputStream.close()方法关闭此文件输入流并释放与该流关联的任何系统资源。

句法:

FileInputStream.close()

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

异常: IOException - 如果发生任何 I/O 错误。

如何调用close() 方法?

第 1 步:将文件附加到 FileInputStream,因为这将使我们能够关闭文件,如下所示:

FileInputStream  fileInputStream =new FileInputStream(“file.txt”);

第 2 步:要关闭文件,我们必须使用上述实例调用 close() 方法。

fileInputStream.close(); 

方法:

1. 我们将首先读取一个文件,然后将其关闭。

2. 关闭文件后,我们会再次尝试读取它。

Java
// Java program to demonstrate the working
// of the FileInputStream close() method
  
import java.io.File;
import java.io.FileInputStream;
  
public class abc {
  
    public static void main(String[] args)
    {
  
        // Creating file object and specifying path
        File file = new File("file.txt");
  
        try {
            FileInputStream input
                = new FileInputStream(file);
            int character;
            // read character by character by default
            // read() function return int between
            // 0 and 255.
  
            while ((character = input.read()) != -1) {
                System.out.print((char)character);
            }
  
            input.close();
            System.out.println("File is Closed");
            System.out.println(
                "Now we will again try to read");
            while ((character = input.read()) != -1) {
                System.out.print((char)character);
            }
        }
        catch (Exception e) {
            System.out.println(
                "File is closed. Cannot be read");
            e.printStackTrace();
        }
    }
}


输出

GeeksforGeeks is a computer science portal
File is Closed
Now we will again try to read
File is closed. Cannot be read
java.io.IOException: Stream Closed
       at java.base/java.io.FileInputStream.read0(Native Method)
       at java.base/java.io.FileInputStream.read(Unknown Source)
       at abc.main(abc.java:28)