Java - FileOutputStream finalize() method



Description

The Java FileOutputStream finalize() method is called by the garbage collector before an object is destroyed. In the case of FileOutputStream, finalize() was traditionally used to ensure that file resources were closed before the object was garbage collected.

Declaration

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

protected void finalize()

Parameters

NA

Return Value

The method does not return any value.

Exception

IOException− If an I/O error occurs.

Example - Usage of FileOutputStream finalize() method

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

FileOutputStreamDemo.java

package com.tutorialspoint;

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

public class FileOutputStreamDemo extends FileOutputStream {

   public FileOutputStreamDemo() throws Exception {
      super("test.txt");
   }

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

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

Output

Assumption

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

ABCDEF

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

Stream is closed successfully.

Example - Using finalize() to Close a FileOutputStream

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

FileOutputStreamDemo.java

package com.tutorialspoint;

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

public class FileOutputStreamDemo {
   static class CustomFileOutputStream extends FileOutputStream {
      public CustomFileOutputStream(String fileName) throws IOException {
         super(fileName);
      }

      @Override
      protected void finalize() throws Throwable {
         System.out.println("Finalize method called. Closing FileOutputStream.");
         this.close(); // Explicitly closing the file output stream
         super.finalize();
      }
   }

   public static void main(String[] args) throws IOException {
      CustomFileOutputStream fos = new CustomFileOutputStream("output.txt");
      fos.write("Hello, World!".getBytes());

      // Making object eligible for garbage collection
      fos = null;

      // Requesting garbage collection
      System.gc();

      System.out.println("Garbage Collection Requested.");
   }
}

Output

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

Garbage Collection Requested.
Finalize method called. Closing FileOutputStream.

Explanation

  • A custom class CustomFileOutputStream extends FileOutputStream and overrides finalize().

  • In finalize(), we print a message and explicitly close the file stream.

  • The fos object is set to null, making it eligible for garbage collection.

  • System.gc() requests garbage collection (though execution is not guaranteed immediately).

  • When garbage collection occurs, finalize() gets called, ensuring the file stream is closed.

Example - Demonstrating Unpredictability of finalize()

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

FileOutputStreamDemo.java

package com.tutorialspoint;

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

public class FileOutputStreamDemo {
   public static void main(String[] args) throws FileNotFoundException, IOException {
      FileOutputStream fos = new FileOutputStream("output.txt");
      fos.write("Testing finalize method.".getBytes());

      // Forgetting to close the stream explicitly
      fos = null;

      // Expecting finalize() to close the file
      System.gc(); 

      System.out.println("Program continues... File may or may not be closed yet.");
   }

   @Override
   protected void finalize() throws Throwable {
      System.out.println("Finalize method invoked.");
      super.finalize();
   }
}

Output()

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

Program continues... File may or may not be closed yet.

Explanation

  • The FileOutputStream is opened and written to, but not explicitly closed.

  • The reference is set to null, making it eligible for garbage collection.

  • System.gc() is called to suggest garbage collection.

  • However, since finalize() execution is unpredictable, the file might not be closed immediately, causing potential resource leaks.

java_io_fileoutputstream.htm
Advertisements