Java.io.FileOutputStream.finalize() Method

Advertisements


Description

The java.io.FileOutputStream.finalize() method cleans up the connection to the file, and ensures that the close method of this file output stream is called when there are no more references to this stream..

Declaration

Following is the declaration for java.io.FileOutputStream.finalize() method:

protected void finalize()

Parameters

  • NA

Return Value

This method does not return any value.

Exception

  • IOException -- if an I/O error occurs..

Example

The following example shows the usage of java.io.FileOutputStream.finalize() method.

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 {
      
      FileOutputStream fos = null;
      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();
      }
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:

ABCDE

Let us compile and run the above program, this will produce the following result:

Stream is closed successfully.



Advertisements
Advertisements