Java FileInputStream finalize() Example
FileInputStream class finalize() method example. This example shows you how to use finalize() method.
Syntax is : protected void finalize() throws IOException
Method ensures that the close method of this file input stream is called when there are no more references to it.
Here is the code.
/**
* @(#) FinalizeFileInputStream.java
* A class representing use of method finalize() of FileInputStream
class in java.io Package.
* @Version 07-June-2008
* @author Rose India Team
*/
import java.io.*;
public class FinalizeFileInputStream extends FileInputStream{
// Contructor definition of the FinalizeFileInputStream class.
public FinalizeFileInputStream() throws IOException{
super("Mahendra.txt"); // call the super class constructor.
}
public static void main(String[] args) throws IOException {
try {
byte[] b = new byte[]{'M','A','H','E','N','D','R','A','S','I','N'};
FileOutputStream fOut = new FileOutputStream("Mahendra.txt");
fOut.write(b);
System.out.print("Content of file : " );
for(int i = 0;i<b.length; i++){
System.out.print((char)b[i]);
}
// Create object of FinalizeFileOutputStream class.
FinalizeFileInputStream objInStream = new FinalizeFileInputStream();
System.out.print("\nElements read : ");
for (int i = 0; i < 8; i++) {
System.out.print((char)objInStream.read());
}
objInStream.finalize();
System.out.print("\nfinalize method is called for this file stream.");
objInStream.read();
}
catch(Exception ex){
System.out.println("\nCan't read more elements bacause file stream"
+" is closed now.");
}
}
} |
output of the program.
Content of file : MAHENDRASIN
Elements read : MAHENDRA
finalize method is called for this file stream.
Can't read more elements bacause file stream is closed now. |
|