Home »
Java programming language
Java FileOutputStream finalize() Method with Example
FileOutputStream Class finalize() method: Here, we are going to learn about the finalize() method of FileOutputStream Class with its syntax and example.
Submitted by Preeti Jain, on April 01, 2020
FileOutputStream Class finalize() method
- finalize() method is available in java.io package.
- finalize() method is used to free connection to the file and it assures that close() method of this FileOutputStream invokes when there is none references exist to this FileOutputStream.
- finalize() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- finalize() method may throw an exception at the time of finalizing the stream.
IOException: This exception may throw while getting any input/output error.
Syntax:
protected void finalize();
Parameter(s):
- It does not accept any parameter.
Return value:
The return type of the method is void, it returns nothing.
Example:
// Java program to demonstrate the example
// of void finalize() method of FileOutputStream
import java.io.*;
public class FinalizeOfFOS extends FileOutputStream {
public FinalizeOfFOS() throws Exception {
super("D:\\includehelp.txt");
}
public static void main(String[] args) throws IOException {
int val;
try {
// Instantiates FinalizeOfFOS
FinalizeOfFOS fos_stm = new FinalizeOfFOS();
// By using write() method is to write
// a byte to fos_stm
fos_stm.write(97);
// By using finalize() method is to free
// memory when no more references exists
System.out.println("finalize() invoked: ");
fos_stm.finalize();
// when we call write() method after
// finalizing the stream will not result an exception
fos_stm.write(99);
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
Output
finalize() invoked: