Course contentsShow
← Java
Lesson 1950 of 2,87039. File I/O: Basic Byte StreamsFree lesson

Best Practices: When to Close and When Not To

Knowing when streams need explicit closure versus when they're managed by higher-level abstractions.

Best Practices: When to Close and When Not To

You'll learn when streams require explicit closure and when they're automatically managed by higher-level abstractions.

Understanding Stream Ownership

Not every stream you encounter needs manual closure. The golden rule: whoever creates the stream is responsible for closing it. If you open a FileInputStream yourself, you must close it. However, if a stream is passed to you as a parameter or wrapped by another component, closing it might not be your responsibility—or could even cause problems.

When You MUST Close

You must close any stream you directly instantiate:

// You created it, you close it
try (FileInputStream fis = new FileInputStream("data.bin");
     BufferedInputStream bis = new BufferedInputStream(fis)) {
    // Both streams auto-close via try-with-resources
}

When wrapping one stream in another (like buffering), close the outermost stream. It will cascade the close operation to wrapped streams.

When NOT to Close

Don't close streams you didn't create:

public void processData(InputStream input) {
    // DO NOT close 'input' here!
    // The caller owns this stream
    byte[] buffer = new byte[1024];
    input.read(buffer);
    // Let the caller decide when to close
}

Don't close System.in, System.out, or System.err: These are standard streams managed by the JVM. Closing them makes them unusable for the rest of your program's execution.

The Wrapper Dilemma

When you wrap a stream (like BufferedInputStream around FileInputStream), closing the wrapper closes the underlying stream automatically. Only close the wrapper, not both:

// GOOD: close only the wrapper
try (BufferedInputStream bis = 
        new BufferedInputStream(new FileInputStream("file.bin"))) {
    // bis.close() will also close the FileInputStream
}

Key Takeaway: Close streams you create using try-with-resources; don't close streams passed to you or standard JVM streams like System.out.