Search code examples
javaobjectinputstream

How to close ObjectInputStream properly?


I'm working with a FileInputStream for the first time and try to load objects (Item) from a file.

This is my code:

    try {

        FileInputStream fi = new FileInputStream(f);
        ObjectInputStream reader = new ObjectInputStream(fi);

        while (true) {
            Item i = (Item)reader.readObject();
            System.out.println(i.getName());
        }

    } catch (Exception e) {
        System.out.println(e.toString());
    }

I've read that this is the standard way to do it and the code works fine. However, this way the fi and reader are never closed, since the compiler jumps to the catch block as soon as an EOFException is thrown.

The compiler doesn't let me close the fi and reader in the catch or a finally block. Is this really how it's supposed to be? How do I close the input objects properly?


Solution

  • You can use try-with-resources statement and that will look like this:

    try (FileInputStream fi = new FileInputStream(f); 
        ObjectInputStream reader = new ObjectInputStream(fi)) {        
    
        while (true) {
            Item i = (Item)reader.readObject();
            System.out.println(i.getName());
        }
    
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    

    Here is documentation to learn more about this approach.