例子
以下示例显示java.io.FileInputStream.finalize()方法的用法。
package com.jc2182;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamAvailable extends FileInputStream {
public FileInputStreamAvailable() throws Exception {
super("C://test.txt");
}
public static void main(String[] args) throws IOException {
int i;
char c;
try {
// create new File input stream
FileInputStreamAvailable fisa = new FileInputStreamAvailable();
// read byte from file input stream
i=fisa.read();
// converts int to char
c = (char)i;
// prints character
System.out.println(c);
// finalize method invoked
fisa.finalize();
// method revoked after finalize metod
i = fisa.read();
c = (char)i;
System.out.println(c);
} catch(Exception ex) {
// if any error occurs
System.out.print("Error: read() invoked after finalize()");
} finally {
// releases all system resources from the streams
if(fis!=null)
fis.close();
}
}
}
假设我们有一个文本文件c:/test.txt ,其内容如下。该文件将用作示例程序的输入-
让我们编译并运行以上程序,这将产生以下结果-
Error: read() invoked after finalize()