Close the stream safely