Duplicate :
|
|
Relates :
|
|
Relates :
|
|
Relates :
|
Name: rm29839 Date: 12/17/97 finalize() method of the FileInputStream and the FileOutputStream calls close() method, which closes the FileDescriptor of the FileInput/OutputStream. This is good while one FileDescriptor is used by exactly one FileInput/OutputStream. If, for example, I open an RandomAccessFile, get the FileDescriptor, create the FileInputStream, use FileInputStream and clear the reference to it, then, when the FileInputStream will be finalized, the RandomAccessFile will be inaccessible. Here the source: import java.io.*; public class IOTest extends FileOutputStream { IOTest(FileDescriptor fd) { super(fd); } public void close() throws IOException { super.close(); System.out.println("The file stream is closed"); } protected void finalize() throws IOException { super.finalize(); System.out.println("The file stream is finalized"); } public static void main(String[] args) throws Exception { RandomAccessFile f = new RandomAccessFile("f", "rw"); IOTest iot = new IOTest(f.getFD()); // Do anything with iot, but don't call iot.close() explicitly. iot = null; // This way to cause finalization seems complicated, // but System.runFinalization() don't finalize iot. try { byte[][] b = new byte[100][]; for (int i = 0; i < b.length; i++) { b[i] = new byte[10000000]; } } catch (OutOfMemoryError e) { } f.writeUTF("The string"); f.close(); } } Here the output of the program: The file stream is closed The file stream is finalized java.io.IOException: write error at java.io.RandomAccessFile.writeUTF(RandomAccessFile.java:842) at IOTest.main(IOTest.java:39) So, f.writeUTF("The string") throws IOException. As I think, FileInput/OutputStream should not have finalize() method, because this classes don't use system resources themself. Instead, finalize() method should be placed in the class FileDescriptor. (Review ID: 22026) ======================================================================
|