Java.io.FileOutputStream.finalize() 方法



描述

java.io.FileOutputStream.finalize() 方法清理與檔案的連線,並確保當沒有更多對該流的引用時,呼叫此檔案輸出流的 close 方法。

宣告

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

protected void finalize()

引數

返回值

此方法不返回值。

異常

IOException - 如果發生 I/O 錯誤。

示例

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

package com.tutorialspoint;

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

public class FileOutputStreamAvailable extends FileOutputStream {

   public FileOutputStreamAvailable() throws Exception {
      super("C://test.txt");
   }

   public static void main(String[] args) throws IOException {
      FileOutputStreamAvailable fosa = null;

      try {
         // create new File input stream
         fosa = new FileOutputStreamAvailable();
         
         // read byte from file input stream
         fosa.finalize();
         
         // converts int to char
         System.out.println("Stream is closed successfully.");
         
      } catch(Exception ex) {
         // if any error occurs
         ex.printStackTrace();
      } finally {
         // releases all system resources from the streams
         if(fos!=null)
            fos.close();
      }
   }
}

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

ABCDE

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

Stream is closed successfully.
java_io_fileoutputstream.htm
廣告