Java中的 FileInputStream finalize() 方法及示例
Java.io.FileInputStream.finalize()方法是Java.io.FileInputStream 类的一部分。它确保在不再存在对 fileInputStream 的引用时调用 fileInputStream 的 close 方法。
- finalize() 方法被注解为@Deprecated。
- finalize() 方法用于在不再存在引用时执行清理操作。
- finalize() 方法可能会抛出 IOException。
- finalize() 方法是受保护的,这意味着不同的包子类不能访问它们。
- FileInputStream.finalize() 在Java.io.* 包中可用。
句法:
protected void finalize() throws IOException
返回类型: finalize() 方法的返回类型为 void,这意味着该方法不返回任何内容。
异常:如果引发任何输入/输出异常,finalize() 方法可能会抛出IOException 。
如何调用finalize() 方法?
第 1 步– 首先,我们必须创建一个扩展 FileInputStream 并将 fileName 传递给其父类的类。
public class GFG extends FileInputStream
{
public GFG()
{
super(fileName);
}
}
第 2 步– 创建我们在第 1 步中创建的类的实例
GFG gfg=new GFG();
第 3 步– 调用 finalize() 方法
gfg.finalize();
下面的程序将说明Java.io.FileInputStream.finalize()方法的使用 -
例子:
Java
// Java Program to illustrate the use of the
// Java.io.FileInputStream.finalize() method
import java.io.*;
import java.io.FileInputStream;
import java.io.IOException;
public class GFG extends FileInputStream {
// parameterized constructor
public GFG(String fileName) throws Exception
{
super(fileName);
}
public static void main(String[] args)
{
try {
// create instance of GFG class that
// extends FileInputStream.
// user should change name of the file
GFG gfg = new GFG("C://geeksforgeeks//tmp.txt");
// reading bytes from file
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());
// finalize() method is called.
// method will perform the cleanup act
// if no reference is available
gfg.finalize();
// reading bytes again from file
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");
}
}
}
输出-
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
从输出中可以清楚地看出,我们可以在调用 finalize() 方法之前甚至之后读取文件。由于 finalize() 方法在仅不存在引用时执行清理操作。
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.