Use try-with-resources to write file

Ensures `close()` is called even on exception.