Re: Closing Files that Weren't Successfully Opened
On Tue, 15 Mar 2011 10:56:46 -0700, Lew wrote:
Michal Kleczek wrote:
Lew wrote:
Michal Kleczek wrote:
Robert Klemme wrote:
If you want BufferedReader you can do
final BufferedReader reader =
?? ??new BufferedReader(new InputStreamReader(new
FileInputStream("foo.txt")));
try {
?? ??for (String line; (line = reader.readLine()) != null;) {
?? ?? ??System.out.println("Found line: " + line);
?? ??}
}
finally {
?? ??reader.close();
}
That only works because both InputStreamReader and BufferedReader
constructors don't throw.
But it is not safe to do the same for: final ObjectInputStream ois =
?? ??new ObjectInputStream(new FileInputStream("foo.txt"));
[snip]
The whole freaking *point* of my post was to show one way to guarantee
release of resources!
Look, make all the legitimate points you want, but don't lie.
You're right - I've read your post again and I admit your way of handling
this does not have problems I wanted to raise. But I was not replying to
_your_ post but to the one cited at the top.
If you just wanted to point out that your way of managing resources
described in another branch of this thread is better - then point taken.
Sometimes it would be good to have destructors...
Nonsense. ??Destructors are to release memory.
Who told you that? :)
This is about external
resources.
And that is also something that destructors can (and should) release.
It's something that should be released, but not necessarily in a
destructor.
True. But:
1. Surely destructors are not only to release memory.
2. _Most of the times_ resources acquired during the lifetime of an
object should be released in the destructor.
For proof, consider that Java doesn't have destructors yet you are still
perfectly capable of releasing resources in a guaranteed way using
'finally'.
I didn't say anywhere that programs written in Java are not capable of
releasing resources in a guaranteed way.
What I said was:
1. This idiom:
final InputStreamWrapper wrapper =
new InputStreamWrapper(new ResourceAcquiringInputStream(resource));
try {
//process wrapper
}
finally {
wrapper.close();
}
while common is dangerous because it _may_ lead to resource leaks.
2. In this particular case (resource acquiring/releasing) I miss
destructors in Java since try/catch/finally construct makes code less
readable when I need to manage several resources.
--
Michal