FileInputStream finalize() Method in Java with Examples
Last Updated :
01 Dec, 2021
Java.io.FileInputStream.finalize() method is a part of Java.io.FileInputStream class. It ensures that the close method of the fileInputStream is called whenever no more references of fileInputStream exist.
- finalize() method is annotated @Deprecated.
- finalize() method is used to perform a cleanup act when no more references exist.
- finalize() method might throw IOException.
- finalize() method is protected, which means different packages subclass cannot access them.
- FileInputStream.finalize() is available in java.io.* package.
Syntax:
protected void finalize​() throws IOException
Return Type: finalize() method has a void return type that means this method does not return anything.
Exception: finalize() method might throw IOException if any Input/output exception raises.
How to invoke finalize() method?
Step 1– First, we must create a class that extends FileInputStream and passes on fileName to its parent class.
public class GFG extends FileInputStream
{
public GFG()
{
super(fileName);
}
}
Step 2– Create an instance of the class that we created in Step 1
GFG gfg=new GFG();
Step 3– invoke the finalize() method
gfg.finalize();
The below program will illustrate the use of the Java.io.FileInputStream.finalize() method-
Example:
Java
import java.io.*;
import java.io.FileInputStream;
import java.io.IOException;
public class GFG extends FileInputStream {
public GFG(String fileName) throws Exception
{
super (fileName);
}
public static void main(String[] args)
{
try {
System.out.println(
"Content read from the file before finalize method is called :" );
for ( int i = 0 ; i <= 13 ; i++)
System.out.print(( char )gfg.read());
gfg.finalize();
System.out.println(
"Content read from the file after finalize method is called :" );
for ( int i = 13 ; i < 47 ; i++)
System.out.print(( char )gfg.read());
}
catch (Throwable t) {
System.out.println( "Some exception" );
}
}
}
|
Output-
Content read from the file before finalize method is called :
GeeksForGeeks
Content read from the file after finalize method is called :
is the best website for programmer
From the output, it is clear that we can read from the file before and even after invoking the finalize() method. Since finalize() method performs the cleanup act when only no reference exists.
tmp.txt
Note: The programs might not run in an online IDE. please use an offline IDE and change the Name of the file according to your need.
Share your thoughts in the comments
Please Login to comment...