Java.io.FileOutputStream.close() 方法



描述

java.io.FileOutputStream.close() 方法關閉此檔案輸出流並釋放與此流關聯的任何系統資源。

宣告

以下是java.io.FileOutputStream.close() 方法的宣告:

public void close()

引數

返回值

此方法不返回值。

異常

示例

以下示例演示了 java.io.FileOutputStream.close() 方法的用法。

package com.tutorialspoint;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      FileOutputStream fos = null;
      
      try {
         // create new file output stream
         fos = new FileOutputStream("C://text.txt");
         
         // close stream
         fos.close();
         
         // try to write into underlying stream
         fos.write(65);
         fos.flush();
         fos.close();
   
      } catch(Exception ex) {
         // if any error occurs
         System.out.print("IOException: File output stream is closed");
      } finally {
         // releases all system resources from the streams
         if(fos!=null)
            fos.close();
      }
   }
}

假設我們有一個文字檔案c:/test.txt,其內容如下。此檔案將用作我們示例程式的輸入:

ABCDEF

讓我們編譯並執行上述程式,這將產生以下結果:

IOException: File output stream is closed
java_io_fileoutputstream.htm
廣告