當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。