Removed print logging; Explicitly check if the stream is closed