If I open a FileInputStream
on File A
, and the program terminates without calling close() method. Will A
be left with a file access handle open or in any other messy state or is it fine?

- 4,634
- 3
- 32
- 51

- 123
- 1
- 5
3 Answers
Usually the garbage collector will clean it up for you at the end of the execution. However it is a very bad practice to not free the resources you are using.
Well, 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.

- 884
- 3
- 11
- 24
Look here (it's in C# but it is the same): What happens to an open Filestream if it is not close due to program crash?
From my experience - the connection closes on its own.
Notice that it is a very bad practice not to close on your own - your will waste your system resources

- 163
- 1
- 6
-
your link relates to a C# situation, the question however asks what happens in Java... – Peter Walser Mar 27 '18 at 10:17
-
the answer is the same for both C# and java – Geek Mar 27 '18 at 10:17
-
Peter Walser you are right - I edited the answer - it is the same and my experience is in java – Lior Alon Mar 27 '18 at 10:20