java – Writing an object to a file. Closing Streams Correctly


I do this:

    try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("path"))) {
    catch (IOException e) {

I use the try-with-resources construction, which, as it were, automatically calls the close () method;

Question 0: Is it possible to do this or is it better to use a regular try block, in which to write flush () and close (), or else, as an option, write close () in a finally () block?

Question1: If you initialize the streams separately, what is the correct way to close them individually?

Question2: Is this construct (try-with-resources) also valid for deserializing an object?


1) you can do this. For this try with resources and created to write less.

2) if you are talking about the example code from the question, then you still have one thread. And if you really want to open multiple streams, then you can do this through a symbol; in parentheses try. The system itself will close them as much as possible.

3) specify what exactly you want to do. I will answer again.

Scroll to Top