Yes you are right.
Garbage collection frees Java heap (memory) but close() frees OS resources used for open file (number of open files is limited on most system) and assures that the data is really written.
But many classes such as FileInputStream
and RandomAccessFile
are written with a finalize() method which ensures that IF an instance in garbage collected, close() will be called first. So in many cases, garbage collection does indirectly free up files, and it is often possible for programmers to be lazy about closing resources, because garbage collection usually cleans them up for you. Unfortunately.
The problem is that you can't control when this happens, and it may not happen at all. So if you have too many files open, the operating system may give you an error about that before the garbage collector gets around to closing them. Or if you want to move a file or delete it, immediately after reading it - the move or delete may fail, because at that moment you've still got the file open for reading.
Errors like this are often hard to reproduce reliably, because they depend on the timing of the garbage collector. So you get things which usually work fine, but sometimes fail mysteriously. Very annoying to debug. For this reason, it is stronly recommended to be sure to close() any stream/reader/connection or other closable resource you may be using, as soon as you are done with it. Preferably in a finally block, to ensure it happens even if some other error occurs in processing.
And with Java 7, there is an addition of AutoClosable
interface, read more about it here.
Ref: http://www.coderanch.com/t/278165//java/InputStream-close-garbage-collection
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…