0

Is there a way to do this?

I'm coding a program that has to iterate for a very long time, and while doing so it is supposed to write to file. I want to close the stream as soon as I terminate the program manually and by doing so, avoid the risk of loosing data because of the unclosed stream. There should be a way of doing this with exception handling, but I'm not sure. Any kind of suggestion is very appreciated!

Thank you

1
  • 1
    Use a try-finally clause where the streams are closed in the finally block. Or, if you're using Java 7, use the try-with-resources block. Commented Dec 9, 2012 at 23:30

3 Answers 3

2

in main:

try {
   startapp();
} finally {
   closeAll();
}

in closeAll() you do what you do for a safe shutdown The code in the finally block will executed even when exceptions will ocure.

Sign up to request clarification or add additional context in comments.

2 Comments

It didn't work... But I found a way out, I will post it in a few seconds
this works! only if you call System.exit() what you never shoul do, it will not work. or when the vm crashes with internal error
1

Using exceptions to control program execution the way you are describing is poor design. It's would be much better to use a shutdown hook.

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
       // Close streams here
    }
});

This will handle most normal shutdowns just fine, though in the case of a hard halt (SIGKILL) the shutdown hooks are not guaranteed to be run. But that is no worse than if you were attempting to close the stream via a finally block.

2 Comments

I tried to test this, but I wasn't able to compile... Still, I already found the problem.
The code above does compile and work for me. What problems did you run into?
0

I found a way! I lost so much time with this, without noticing that streams are automatically closed when the program terminates...

Data hadn't been written because I wasn't using the flush() method after the write() method, like this:

out.write(line);
out.flush();

Thank you all for your help

1 Comment

this is not an answer to your question! close the file, when you dont need it anymore. out.close()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.