closing streams correctly to avoid resource leaks