Re: Quick Question
On 2/11/2015 12:56 PM, Doug Mika wrote:
I have code that I need to execute upon the user closing my program. To be exact I need to close the file stream when the user closes my application. How can I program this? There are no destructors in Java, and that was one idea I had but destructors aren't always called?
(I guess you mean "finalizers" by that second "destructors," but it
doesn't make much difference: They're not guaranteed to be called.)
There are several approaches, suitable for several different kinds
of program structure. In roughly descending order of ease and general
suitability:
- If the creation, use, and closing of the file stream can take
place within a single code block (which may, of course, call as many
other methods and things as it likes), consider "try with resources:"
try (Stream stream = ...) {
// lots of code using the open `stream'
}
// `stream' is closed automatically when the `try' block
// completes, either normally or abruptly
- The "try" approach won't work if method M() opens the stream and
it's to stay open even after M() returns. So next I'd look at how the
user closes your program: Does he click on a "STOP" button, or type
Ctrl-D, or what? Add a "close the stream if it's still open" call to
the code that handles each such event, and you're all set. If the
user halts your program by closing its main window (maybe via an O/S-
supplied little red X or something), you can register a WindowListener
to be informed of the closing event, and have it close the stream.
- Finally, there's Runtime.addShutdownHook(). With this method
you can arrange to have some code run while the JVM is shutting down
(if "your program stops" implies "JVM shuts down"). Unfortunately,
while it's easy to make the arrangements to run some code, the code
itself is rather tricky to write -- just read the scary-sounding
language in its Javadoc, and you'll see what I mean.
There may be other possibilities, too, depending on how your
program is structured, how the stream gets opened, and how the user
stops the program.
--
esosman@comcast-dot-net.invalid
"Don't be afraid of work. Make work afraid of you." -- TLM