当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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)

Note:This code will not run on an online IDE as it requires a file on the system.




相关用法


注:本文由纯净天空筛选整理自akshitsaxenaa09大神的英文原创作品 FileInputStream close() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。