Close stream when writing